PHPackages                             roaresearch/yii2-oauth2-server - 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. roaresearch/yii2-oauth2-server

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

roaresearch/yii2-oauth2-server
==============================

OAuth2 Server for PHP

7.0.0(3y ago)22.7k1MITPHPPHP ~8.1

Since Nov 26Pushed 3y ago1 watchersCompare

[ Source](https://github.com/ROAResearch/yii2-oauth2-server)[ Packagist](https://packagist.org/packages/roaresearch/yii2-oauth2-server)[ Docs](https://github.com/roaresearch/yii2-oauth2-server)[ RSS](/packages/roaresearch-yii2-oauth2-server/feed)WikiDiscussions main Synced yesterday

READMEChangelog (2)Dependencies (11)Versions (4)Used By (1)

Yii2 OAuth2 Server
==================

[](#yii2-oauth2-server)

A wrapper for implementing an [OAuth2 Server](https://github.com/bshaffer/oauth2-server-php).

[![Latest Stable Version](https://camo.githubusercontent.com/f2643924f4f0220628b048766a6a4c58f76c3e4d81698c6036f3388c12588c7c/68747470733a2f2f706f7365722e707567782e6f72672f726f6172657365617263682f796969322d6f61757468322d7365727665722f762f737461626c65)](https://packagist.org/packages/roaresearch/yii2-oauth2-server)[![Total Downloads](https://camo.githubusercontent.com/211c0bc49f22504c59d341f1d0f97a09bbb61eca1565c8e599feddee8c68ab50/68747470733a2f2f706f7365722e707567782e6f72672f726f6172657365617263682f796969322d6f61757468322d7365727665722f646f776e6c6f616473)](https://packagist.org/packages/roaresearch/yii2-oauth2-server)[![Code Coverage](https://camo.githubusercontent.com/2aa45cc21ffc307497095bb5c3ec53bef5a7326bc9d06e907f2d1f3f5a60334c/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f726f6172657365617263682f796969322d6f61757468322d7365727665722f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/roaresearch/yii2-oauth2-server/?branch=master)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/02d72a4d38aaf2eb6b1b22f42257857b04440fb842eb3119321024921ecd363b/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f726f6172657365617263682f796969322d6f61757468322d7365727665722f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/roaresearch/yii2-oauth2-server/?branch=master)

Scrutinizer [![Build Status Scrutinizer](https://camo.githubusercontent.com/97a4ed634fab6ec40c9e78aa573701f9758e4747a28f73fbc2ef178c9f28fc2f/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f726f6172657365617263682f796969322d6f61757468322d7365727665722f6261646765732f6275696c642e706e673f623d6d6173746572267374796c653d666c6174)](https://scrutinizer-ci.com/g/roaresearch/yii2-oauth2-server/build-status/master)

This project was forked from [Filsh Original Project](https://github.com/Filsh/yii2-oauth2-server) but the changes are not transparent, read \[UPGRADE.md\] to pass to the latest version.

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

[](#installation)

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

Either run

```
php composer.phar require --prefer-dist roaresearch/yii2-oauth2-server "*"

```

or add

```
"roaresearch/yii2-oauth2-server": "~6.0.0"
```

to the require section of your composer.json.

Usage
-----

[](#usage)

To use this extension, simply add the following code in your application configuration as a new module:

```
    'bootstrap' => ['oauth2'],
    'modules'=>[
        // other modules ...
        'oauth2' => [
            'class' => \roaresearch\yii2\oauth2server\Module::class,
            'tokenParamName' => 'accessToken',
            'tokenAccessLifetime' => 3600 * 24,
            'storageMap' => [
                'user_credentials' => 'app\models\User',
            ],
            'grantTypes' => [
                'user_credentials' => [
                    'class' => 'OAuth2\GrantType\UserCredentials',
                ],
                'refresh_token' => [
                    'class' => 'OAuth2\GrantType\RefreshToken',
                    'always_issue_new_refresh_token' => true
                ],
            ],
        ],
    ],
```

Bootstrap will initialize translation and add the required url rules to `Yii::$app->urlManager`.

### JWT tokens

[](#jwt-tokens)

There is no JWT token support on this fork, feel free to submit a (pull request)\[\] to enable this functionality.

### UserCredentialsInterface

[](#usercredentialsinterface)

The class passed to `Yii::$app->user->identityClass` must implement the interface `\OAuth2\Storage\UserCredentialsInterface`, to store oauth2 credentials in user table.

```
use Yii;

class User extends common\models\User implements
    \OAuth2\Storage\UserCredentialsInterface
{

    /**
     * Implemented for Oauth2 Interface
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        /** @var \roaresearch\yii2\oauth2server\Module $module */
        $module = Yii::$app->getModule('oauth2');
        $token = $module->getServer()->getResourceController()->getToken();
        return !empty($token['user_id'])
            ? static::findIdentity($token['user_id'])
            : null;
    }

    /**
     * Implemented for Oauth2 Interface
     */
    public function checkUserCredentials($username, $password)
    {
        $user = static::findByUsername($username);
        if (empty($user)) {
            return false;
        }
        return $user->validatePassword($password);
    }

    /**
     * Implemented for Oauth2 Interface
     */
    public function getUserDetails($username)
    {
        $user = static::findByUsername($username);
        return ['user_id' => $user->getId()];
    }
}
```

### Migrations

[](#migrations)

The next step is to run migrations

```
yii migrate all -p=@roaresearch/yii2/oauth2server/migrations/tables
yii fixture "*" -n=roaresearch\\yii2\\oauth2server\\fixtures
```

The first commando create the OAuth2 database scheme. The second command insert test client credentials `testclient:testpass` for `http://fake/`.

### Controllers

[](#controllers)

To support authentication by access token. Simply add the behaviors for your controller or module.

```
use yii\{
    helpers\ArrayHelper,
    auth\HttpBearerAuth,
    filters\auth\QueryParamAuth,
};
use roasearch\yii2\oauth2server\filters\auth\CompositeAuth;

class Controller extends \yii\rest\Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            'authenticator' => [
                'class' => CompositeAuth::class,
                'authMethods' => [
                    ['class' => HttpBearerAuth::class],
                    [
                        'class' => QueryParamAuth::class,
                        'tokenParam' => 'accessToken',
                    ],
                ],
            ],
        ]);
    }
}
```

The code above is the same as the default implementation which can be simplified as:

```
use yii\helpers\ArrayHelper;
use roaresearch\yii2\oauth2server\filters\auth\CompositeAuth;

class Controller extends \yii\rest\Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            'authenticator' => CompositeAuth::class,
        ]);
    }
}
```

### Scopes

[](#scopes)

The property `roaresearch\yii2\oauth2server\filters\auth\CompositeAuth::$actionScopes`set which actions require specific scopes. If those scopes are not meet the action wont be executed, and the server will reply with an HTTP Status Code 403.

```
public function behaviors()
{
    return ArrayHelper::merge(parent::behaviors(), [
        'authenticator' => [
            'class' => CompositeAuth::class,
            'actionScopes' => [
                'create' => 'default create',
                'update' => 'default edit',
                '*' => 'default', // wildcards are allowed
            ],
        ],,
    ]);
}
```

### Automatically Revoke Tokens

[](#automatically-revoke-tokens)

Sometimes its neccessary to revoke a token on each request to prevent the request from being triggered twice.

To enable this functionality you need to implement `roaresearch\yii2\oauth2server\RevokeAccessTokenInterface` in the class used to identify the authenticated user.

```
use OAuth2\Storage\UserCredentialsInterface;
use roaresearch\yii2\oauth2server\{
    RevokeAccessTokenInterface,
    RevokeAccessTokenTrait,
};

class User extend \yii\db\ActiveRecord implement
    UserCredentialsInterface,
    RevokeAccessTokenInterface
{
    use RevokeAccessTokenTrait; // optional, trait with default implementation.

    // rest of the class.
}
```

Then use the previous class as configuration for `Yii::$app->user->identityClass`

Attaching the action filter `roaresearch\yii2\oauth2server\filters\RevokeAccessToken`allows to configure the actions to automatically revoke the access token.

```
public function behaviors()
{
    return [
        'revokeToken' => [
            'class' => \roaresearch\yii2\oauth2server\filters\RevokeAccessToken::class,
            // optional only revoke the token if it has any of the following
            // scopes. if not defined it will always revoke the token.
            'scopes' => ['author', 'seller'],
            // optional whether or not revoke all tokens or just the active one
            'revokeAll' => true,
            // optional if non authenticated users are permited.
            'allowGuests' => true,
            // which actions this behavior applies to.
            'only' => ['create', 'update'],
        ],
    ];
}
```

### Generate Token with JS

[](#generate-token-with-js)

To get access token (js example):

```
var url = window.location.host + "/oauth2/token";
var data = {
    'grant_type':'password',
    'username':'',
    'password':'',
    'client_id':'testclient',
    'client_secret':'testpass'
};
//ajax POST `data` to `url` here
//
```

Authorize Action
----------------

[](#authorize-action)

Action used to generate access codes for external servers. To test its use first run the provided fixtures so the testclient is loaded into the database.

```
composer run-fixtures

```

If the test url you are using is not on the default uri list, you will have to modify the information on the table `oauth_clients` in your database.

Then you can test the access code generation by accessing the Yii2 uri

```
/WEB/authorize?client_id=testclient&response_type=code&state=xyz&redirect_uri=http://127.0.0.1:8080/

```

Which must show a minimal form with just 2 buttons to choose whether you deny or authorize. If you authorize a new access code will be generated and will redirect to:

```
http://127.0.0.1:8080/?code=[access code]6&state=xyz

```

If you deny access, it will redirect to the same URI with an error code instead.

You can use the class `roaresearch\yii2\oauth2server\actions\AuthorizeAction` to declare authorize actions at any controller you want.

```
use roaresearch\yii2\oauth2server\actions\AuthorizeAction;

class SiteController extends Controller
{
    public function actions()
    {
        return [
            'authorize' => [
                'class' => AuthorizeAction::class,
                'loginUri' => ['site/login'],
                'viewRoute' => 'authorize',
                'oauth2Module' => 'api/oauth2',
            ],
        ];
    }
}
```

Built With
----------

[](#built-with)

- Yii 2: The Fast, Secure and Professional PHP Framework

Code of Conduct
---------------

[](#code-of-conduct)

Please read [CODE\_OF\_CONDUCT.md](CODE_OF_CONDUCT.md) for details on our code of conduct.

Contributing
------------

[](#contributing)

Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on the process for submitting pull requests to us.

Versioning
----------

[](#versioning)

We use [SemVer](http://semver.org/) for versioning. For the versions available, see the [tags on this repository](/tags).

*Considering [SemVer](http://semver.org/) for versioning rules 9, 10 and 11 talk about pre-releases, they will not be used.*

Authors
-------

[](#authors)

- [**Angel Guevara**](https://github.com/Faryshta) - *Initial work*
- [**Carlos Llamosas**](https://github.com/neverabe) - *Initial work*

See also the list of [contributors](/graphs/contributors) who participated in this project.

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details

For more, see

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity21

Limited adoption so far

Community21

Small or concentrated contributor base

Maturity68

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

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 ~1067 days

Total

2

Last Release

1292d ago

Major Versions

5.0.0 → 7.0.02022-10-28

PHP version history (2 changes)5.0.0PHP &gt;=7.1

7.0.0PHP ~8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/2341d88f3cdea0c2474cfbf59e5cf6dab5dd6a026d7846fabf219f2a93be1641?d=identicon)[neverabe](/maintainers/neverabe)

---

Top Contributors

[![Faryshta](https://avatars.githubusercontent.com/u/2029247?v=4)](https://github.com/Faryshta "Faryshta (58 commits)")[![filsh](https://avatars.githubusercontent.com/u/6173680?v=4)](https://github.com/filsh "filsh (46 commits)")[![neverabe](https://avatars.githubusercontent.com/u/1173807?v=4)](https://github.com/neverabe "neverabe (14 commits)")[![mtangoo](https://avatars.githubusercontent.com/u/1502872?v=4)](https://github.com/mtangoo "mtangoo (4 commits)")[![zacksleo](https://avatars.githubusercontent.com/u/3369169?v=4)](https://github.com/zacksleo "zacksleo (3 commits)")[![Sasha-Ch](https://avatars.githubusercontent.com/u/94524537?v=4)](https://github.com/Sasha-Ch "Sasha-Ch (3 commits)")[![freezy-sk](https://avatars.githubusercontent.com/u/661637?v=4)](https://github.com/freezy-sk "freezy-sk (2 commits)")[![roaresearch-creator](https://avatars.githubusercontent.com/u/57551213?v=4)](https://github.com/roaresearch-creator "roaresearch-creator (2 commits)")[![hiqsol](https://avatars.githubusercontent.com/u/11820365?v=4)](https://github.com/hiqsol "hiqsol (1 commits)")[![lisps](https://avatars.githubusercontent.com/u/5764551?v=4)](https://github.com/lisps "lisps (1 commits)")[![Dareen](https://avatars.githubusercontent.com/u/5462442?v=4)](https://github.com/Dareen "Dareen (1 commits)")[![damiandennis](https://avatars.githubusercontent.com/u/1276622?v=4)](https://github.com/damiandennis "damiandennis (1 commits)")[![pdanzinger](https://avatars.githubusercontent.com/u/11884180?v=4)](https://github.com/pdanzinger "pdanzinger (1 commits)")[![FopherC](https://avatars.githubusercontent.com/u/1615875?v=4)](https://github.com/FopherC "FopherC (1 commits)")[![RoyXiang](https://avatars.githubusercontent.com/u/1772811?v=4)](https://github.com/RoyXiang "RoyXiang (1 commits)")[![brutto](https://avatars.githubusercontent.com/u/954379?v=4)](https://github.com/brutto "brutto (1 commits)")[![shcherbanich](https://avatars.githubusercontent.com/u/3122336?v=4)](https://github.com/shcherbanich "shcherbanich (1 commits)")[![SimonSoftware](https://avatars.githubusercontent.com/u/6181879?v=4)](https://github.com/SimonSoftware "SimonSoftware (1 commits)")[![tibee](https://avatars.githubusercontent.com/u/3636947?v=4)](https://github.com/tibee "tibee (1 commits)")[![wilberto-dzul](https://avatars.githubusercontent.com/u/7696969?v=4)](https://github.com/wilberto-dzul "wilberto-dzul (1 commits)")

---

Tags

oauthoauth2extensionmoduleyii

###  Code Quality

TestsCodeception

### Embed Badge

![Health badge](/badges/roaresearch-yii2-oauth2-server/health.svg)

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

###  Alternatives

[filsh/yii2-oauth2-server

OAuth2 Server for PHP

331523.9k12](/packages/filsh-yii2-oauth2-server)[budyaga/yii2-users

Module for manage users and their rights with the support of registration through social services and assigned to each user more than one social service.

409.1k](/packages/budyaga-yii2-users)

PHPackages © 2026

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