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

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

tecnocen/yii2-oauth2-server
===========================

OAuth2 Server for PHP

4.1.1(7y ago)813.5k22MITPHPPHP &gt;=5.6

Since Nov 15Pushed 6y ago2 watchersCompare

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

READMEChangelog (7)Dependencies (8)Versions (8)Used By (2)

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/e8d2fc3bb372e6821019dc4ee27feef89043fb1ab05142c5dda47ea4ba7c9a72/68747470733a2f2f706f7365722e707567782e6f72672f7465636e6f63656e2f796969322d6f61757468322d7365727665722f762f737461626c65)](https://packagist.org/packages/tecnocen/yii2-oauth2-server)[![Total Downloads](https://camo.githubusercontent.com/768b1a6c8c26c1057ab784fc03dfb571223739684ff3686e413d140b53669c6c/68747470733a2f2f706f7365722e707567782e6f72672f7465636e6f63656e2f796969322d6f61757468322d7365727665722f646f776e6c6f616473)](https://packagist.org/packages/tecnocen/yii2-oauth2-server)

Travis [![Build Status Travis](https://camo.githubusercontent.com/30d33cd12be54fa0710890cd38b6288003080ad3df07374c5fce9ef6140737b1/68747470733a2f2f7472617669732d63692e6f72672f7465636e6f63656e2d636f6d2f796969322d6f61757468322d7365727665722e7376673f6272616e63683d6d6173746572267374796c653d666c61743f7374796c653d666f722d7468652d6261646765)](https://travis-ci.org/tecnocen-com/yii2-oauth2-server)

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 tecnocen/yii2-oauth2-server "*"

```

or add

```
"tecnocen/yii2-oauth2-server": "~4.1"
```

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' => 'tecnocen\oauth2server\Module',
            '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 \tecnocen\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=@tecnocen/oauth2server/migrations/tables
yii fixture "*" -n=tecnocen/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;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;
use tecnocen\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 tecnocen\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 `tecnocen\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 `tecnocen\oauth2server\RevokeAccessTokenInterface` in the class used to identify the authenticated user.

```
use OAuth2\Storage\UserCredentialsInterface;
use tecnocen\oauth2server\RevokeAccessTokenInterface;
use tecnocen\oauth2server\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 `tecnocen\oauth2server\filters\RevokeAccessToken`allows to configure the actions to automatically revoke the access token.

```
public function behaviors()
{
    return [
        'revokeToken' => [
            'class' => \tecnocen\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
//
```

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](https://github.com/tecnocen-com/yii2-oauth2-server/blob/master/CODE_OF_CONDUCT.md) for details on our code of conduct.

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

[](#contributing)

Please read [CONTRIBUTING.md](https://github.com/tecnocen-com/yii2-oauth2-server/blob/master/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](https://github.com/tecnocen-com/yii2-oauth2-server/tags).

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

Authors
-------

[](#authors)

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

See also the list of [contributors](https://github.com/tecnocen-com/yii2-oauth2-server/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

Acknowledgments
---------------

[](#acknowledgments)

- TO DO - Hat tip to anyone who's code was used
- TO DO - Inspiration
- TO DO - etc

[![yii2-oauth2-server](https://camo.githubusercontent.com/27efd385b52d1f80968b87f3433de1f0c57983e900c12ba71c451faf51ffb62c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f506f77657265645f5f62792d5465636e6f63656e2e636f6d2d6f72616e67652e7376673f7374796c653d666f722d7468652d6261646765)](https://www.tecnocen.com/)

For more, see

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity29

Limited adoption so far

Community26

Small or concentrated contributor base

Maturity63

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

Recently: every ~102 days

Total

7

Last Release

2672d ago

Major Versions

3.0.2 → 4.0.02018-08-11

### Community

Maintainers

![](https://www.gravatar.com/avatar/3d5f64412ef020f8c137ff5c7f5e4a0866271f2f9ba9584e5a24aa48467f958d?d=identicon)[Faryshta](/maintainers/Faryshta)

![](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 (49 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 (11 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)")[![hector-del-rio](https://avatars.githubusercontent.com/u/9391691?v=4)](https://github.com/hector-del-rio "hector-del-rio (1 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)")[![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)")[![FopherC](https://avatars.githubusercontent.com/u/1615875?v=4)](https://github.com/FopherC "FopherC (1 commits)")

---

Tags

oauthoauth2extensionmoduleyii

### Embed Badge

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

```
[![Health](https://phpackages.com/badges/tecnocen-yii2-oauth2-server/health.svg)](https://phpackages.com/packages/tecnocen-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)
