PHPackages                             virginent/oauth2 - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. virginent/oauth2

ActiveYii2-extension[Authentication &amp; Authorization](/categories/authentication)

virginent/oauth2
================

The Oauth2 Server extension for the Yii2 framework

2.0(5y ago)03MITPHP

Since Jul 13Pushed 5y agoCompare

[ Source](https://github.com/VirginEnt/yii2-oauth2-server)[ Packagist](https://packagist.org/packages/virginent/oauth2)[ Docs](https://github.com/virginent/yii2-oauth2-server)[ RSS](/packages/virginent-oauth2/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (4)Versions (16)Used By (0)

Yii2 OAuth 2.0 Server
=====================

[](#yii2-oauth-20-server)

Description
-----------

[](#description)

This extension provides simple implementation of [Oauth 2.0](http://tools.ietf.org/wg/oauth/draft-ietf-oauth-v2/) specification using Yii2 framework.

Installation
------------

[](#installation)

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

To install, either run

```
$ php composer.phar require virginent/oauth2 "*"

```

or add

```
"virginent/oauth2": "*"

```

to the `require` section of your `composer.json` file.

Migrations are available from [migrations](./src/migrations) folder.

To add migrations to your application, edit the console config file to configure [a namespaced migration](http://www.yiiframework.com/doc-2.0/guide-db-migrations.html#namespaced-migrations):

```
'controllerMap' => [
    // ...
    'migrate' => [
        'class' => 'yii\console\controllers\MigrateController',
        'migrationPath' => null,
        'migrationNamespaces' => [
            // ...
            'virginent\oauth2\migrations',
        ],
    ],
],
```

Then issue the `migrate/up` command:

```
yii migrate/up
```

You also need to specify message translation source for this package:

```
'components' => [
    'i18n' => [
        'translations' => [
            'virginent/oauth2' => [
                'class' => \yii\i18n\PhpMessageSource::class,
                'basePath' => '@virginent/oauth2/messages',
            ],
        ],
    ]
],

```

Usage
-----

[](#usage)

OAuth 2.0 Authorization usage

```
namespace app\controllers;

use app\models\LoginForm;

class AuthController extends \yii\web\Controller
{
    public function behaviors()
    {
        return [
            /**
             * Checks oauth2 credentions and try to perform OAuth2 authorization on logged user.
             * AuthorizeFilter uses session to store incoming oauth2 request, so
             * you can do additional steps, such as third party oauth authorization (Facebook, Google ...)
             */
            'oauth2Auth' => [
                'class' => \virginent\oauth2\AuthorizeFilter::className(),
                'only' => ['index'],
            ],
        ];
    }
    public function actions()
    {
        return [
            /**
             * Returns an access token.
             */
            'token' => [
                'class' => \virginent\oauth2\TokenAction::classname(),
            ],
            /**
             * OPTIONAL
             * Third party oauth providers also can be used.
             */
            'back' => [
                'class' => \yii\authclient\AuthAction::className(),
                'successCallback' => [$this, 'successCallback'],
            ],
        ];
    }
    /**
     * Display login form, signup or something else.
     * AuthClients such as Google also may be used
     */
    public function actionIndex()
    {
        $model = new LoginForm();
        if ($model->load(\Yii::$app->request->post()) && $model->login()) {
            if ($this->isOauthRequest) {
                $this->finishAuthorization();
            } else {
                return $this->goBack();
            }
        } else {
            return $this->render('index', [
                'model' => $model,
            ]);
        }
    }
    /**
     * OPTIONAL
     * Third party oauth callback sample
     * @param OAuth2 $client
     */
    public function successCallback($client)
    {
        switch ($client::className()) {
            case GoogleOAuth::className():
                // Do login with automatic signup
                break;
            ...
            default:
                break;
        }
        /**
         * If user is logged on, redirects to oauth client with success,
         * or redirects error with Access Denied
         */
        if ($this->isOauthRequest) {
            $this->finishAuthorization();
        }
    }

}
```

Api controller sample

```
class ApiController extends \yii\rest\Controller
{
    public function behaviors()
    {
        return [
            /**
             * Performs authorization by token
             */
            'tokenAuth' => [
                'class' => \virginent\oauth2\TokenAuth::className(),
            ],
        ];
    }
    /**
     * Returns username and email
     */
    public function actionIndex()
    {
        $user = \Yii::$app->user->identity;
        return [
            'username' => $user->username,
            'email' =>  $user->email,
        ];
    }
}
```

Sample client config

```
return [
...
   'components' => [
       'authClientCollection' => [
            'class' => 'yii\authclient\Collection',
            'clients' => [
                'myserver' => [
                    'class' => 'yii\authclient\OAuth2',
                    'clientId' => 'unique client_id',
                    'clientSecret' => 'client_secret',
                    'tokenUrl' => 'http://myserver.local/auth/token',
                    'authUrl' => 'http://myserver.local/auth/index',
                    'apiBaseUrl' => 'http://myserver.local/api',
                ],
            ],
        ],
];
```

If you want to use Resource Owner Password Credentials Grant, implement `\virginent\oauth2\OAuth2IdentityInterface`.

```
use virginent\oauth2\OAuth2IdentityInterface;

class User extends ActiveRecord implements IdentityInterface, OAuth2IdentityInterface
{
    ...

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findIdentityByUsername($username)
    {
        return static::findOne(['username' => $username]);
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    ...
}
```

### Warning

[](#warning)

As official documentation says:

> Since this access token request utilizes the resource owner's password, the authorization server MUST protect the endpoint against brute force attacks (e.g., using rate-limitation or generating alerts).

It's strongly recommended to rate limits on token endpoint. Fortunately, Yii2 have instruments to do this.

For further information see [Yii2 Ratelimiter](http://www.yiiframework.com/doc-2.0/yii-filters-ratelimiter.html)

License
-------

[](#license)

**virginent/oauth2** is released under the MIT License. See the bundled `LICENSE` for details.

###  Health Score

29

—

LowBetter than 59% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity3

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity71

Established project with proven stability

 Bus Factor1

Top contributor holds 51.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~155 days

Recently: every ~350 days

Total

14

Last Release

1942d ago

Major Versions

1.7.1 → 2.02021-01-22

### Community

Maintainers

![](https://www.gravatar.com/avatar/e36065a8c32347850fcd294c743c14fe668f52965c3c5569a6935bab35ba7f6d?d=identicon)[VirginEnt](/maintainers/VirginEnt)

---

Top Contributors

[![borodulin](https://avatars.githubusercontent.com/u/8121448?v=4)](https://github.com/borodulin "borodulin (37 commits)")[![alexeevdv](https://avatars.githubusercontent.com/u/597839?v=4)](https://github.com/alexeevdv "alexeevdv (22 commits)")[![atakajlo](https://avatars.githubusercontent.com/u/5870060?v=4)](https://github.com/atakajlo "atakajlo (8 commits)")[![VirginEnt](https://avatars.githubusercontent.com/u/3253221?v=4)](https://github.com/VirginEnt "VirginEnt (2 commits)")[![gerysk](https://avatars.githubusercontent.com/u/16836790?v=4)](https://github.com/gerysk "gerysk (1 commits)")[![karakum](https://avatars.githubusercontent.com/u/12033941?v=4)](https://github.com/karakum "karakum (1 commits)")[![noam148](https://avatars.githubusercontent.com/u/10885039?v=4)](https://github.com/noam148 "noam148 (1 commits)")

---

Tags

oauth2yii2oauth2 server

###  Code Quality

TestsCodeception

### Embed Badge

![Health badge](/badges/virginent-oauth2/health.svg)

```
[![Health](https://phpackages.com/badges/virginent-oauth2/health.svg)](https://phpackages.com/packages/virginent-oauth2)
```

###  Alternatives

[conquer/oauth2

The Oauth2 Server extension for the Yii2 framework

76112.9k5](/packages/conquer-oauth2)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
