PHPackages                             gbksoft/yii2-tokens - 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. gbksoft/yii2-tokens

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

gbksoft/yii2-tokens
===================

Yii 2 custom tokens architecture for authorization

1.0.1(10y ago)22.3k—0%MITPHP

Since Feb 4Pushed 10y ago2 watchersCompare

[ Source](https://github.com/gbksoft/yii2-tokens)[ Packagist](https://packagist.org/packages/gbksoft/yii2-tokens)[ RSS](/packages/gbksoft-yii2-tokens/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependencies (2)Versions (3)Used By (0)

Tokens Module for Yii 2
=======================

[](#tokens-module-for-yii-2)

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

[](#installation)

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

Either run

```
php composer.phar require gbksoft/yii2-tokens

```

or add

```
"gbksoft/yii2-tokens": "~1.0.0"

```

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

Usage
-----

[](#usage)

Module configurations:

```
...
    'modules' => [
        'tokens' => [
            'class' => 'gbksoft\modules\tokens\Module',
            'userClass' => common\models\User::class,
            'urlRulePrefix' => 'v1/',
            'on beforeControllerBehavior' => function($event) {
                // Update behaviors on module controller "User"
                $event->data = common\overrides\rest\ActiveController::getDefaultBehaviors();
            },
        ],
    ],
...
```

Change table name for relations to users table. Console application event for change `{{%user}}` table name in module migrations example:

```
    'on beforeUserTokenMigrateUp' => function($event) {
        // $event->sender is Migration class
        // $event->sender->usersTableName default value is "{{%user}}"
        $event->sender->usersTableName = '{{%users}}';
    }

```

Use controllerMap in console config:

```
    'controllerMap' => [
        'migrate' => [
            'class' => 'console\controllers\MigrateController',
            'migrationLookup' => [
                '@console/migrations',
                '@vendor/gbksoft/yii2-tokens/migrations',
            ]
        ]
    ],

```

In IdentityInterface (User model)

```
use yii\web\UnauthorizedHttpException;
use gbksoft\modules\tokens\models\UserToken;

...

class User extends ActiveRecord implements IdentityInterface
{
    ...

    public $userToken;

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        /** @var $userToken \common\models\UserToken */
        $userToken = UserToken::find()
            ->andWhere(['=', 'token', $token])
            ->one();

        if (!$userToken) {
            throw new UnauthorizedHttpException('Bad token');
        }

        if (!$userToken->user) {
            throw new UnauthorizedHttpException('User not found');
        }

        if ($userToken->user->status == self::STATUS_DELETED) {
            throw new UnauthorizedHttpException('This user has deleted');
        }

        if (!$userToken->matchIp(Yii::$app->getRequest()->userIP)) {
            throw new UnauthorizedHttpException('Differed user token IP-s');
        }

        if ($userToken->expired()) {
            throw new UnauthorizedHttpException('User token is expired');
        }

        $user = $userToken->getUser()->one();
        $user->userToken = $userToken;

        return $user;
    }

    ...
}
```

Login action example

```
namespace api\versions\v1\controllers\user;

use Yii;
use yii\web\ServerErrorHttpException;
use gbksoft\modules\tokens\models\UserToken;

class LoginAction extends \yii\rest\CreateAction {
    /**
     * Field name of body parameter for remember
     * @var string
     */
    public $rememberField = 'remember';

    /**
     * Confirm value of body parameter for remember
     * @var array
     */
    public $rememberYesValue = 'yes';

    /**
     * Confirm value of body parameter for not remember
     * @var array
     */
    public $rememberNoValue = 'no';

    /**
     * Field name of body parameter for verify_ip
     * @var string
     */
    public $verifyIpField = 'verify_ip';

    /**
     * Confirm value of body parameter for verify_ip
     * @var array
     */
    public $verifyIpYesValue = 'yes';

    /**
     * If remember me expire time as seconds
     * @var integer
     */
    public $expireSecondsRemember = 604800; // One week
    /**
     * If not remember me expire time as seconds
     * @var integer
     */
    public $expireSecondsNotRemember = 3600; // One hour

    /**
     * Creates a new model.
     * @return \yii\db\ActiveRecordInterface the model newly created
     * @throws ServerErrorHttpException if there is any error when creating the model
     */
    public function run()
    {
        if ($this->checkAccess) {
            call_user_func($this->checkAccess, $this->id);
        }

        /** @var $model \common\models\User */
        $model = new $this->modelClass([
            'scenario' => $this->scenario,
        ]);

        /** @var $request \yii\web\Request */
        $request = Yii::$app->getRequest();

        $model->load($request->getBodyParams(), '');

        if ($model->login($model)) {

            $rememberValue = $request->getBodyParam($this->rememberField);
            $verifyIP = ($request->getBodyParam($this->verifyIpField) == $this->verifyIpYesValue);

            switch ($rememberValue) {
                case $this->rememberYesValue:
                    $remember = true;
                    $seconds = $this->expireSecondsRemember;
                    break;
                case $this->rememberNoValue:
                    $remember = false;
                    $seconds = $this->expireSecondsNotRemember;
                    break;
                default:
                    $remember = false;
                    $seconds = UserToken::EXPIRE_DEFAULT_SECONDS;
            }

            /* @var $userToken \common\models\UserToken */
            $userToken = UserToken::createForUser(Yii::$app->user->identity, $seconds, $remember, $verifyIP);

            if ($userToken) {
                return $userToken;
            } else {
                throw new ServerErrorHttpException('Failed to create the object for user token.');
            }

        } elseif (!$model->hasErrors()) {
            throw new ServerErrorHttpException('Failed login.');
        }

        return $model;
    }
}
```

Console command for clear expired tokens

```
./yii tokens/tokens/clear-expired
```

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity20

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 100% 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 ~6 days

Total

2

Last Release

3745d ago

### Community

Maintainers

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

---

Top Contributors

[![littlefuntik](https://avatars.githubusercontent.com/u/876937?v=4)](https://github.com/littlefuntik "littlefuntik (26 commits)")

---

Tags

tokensauthorizationyii2extensionmoduleBearer

### Embed Badge

![Health badge](/badges/gbksoft-yii2-tokens/health.svg)

```
[![Health](https://phpackages.com/badges/gbksoft-yii2-tokens/health.svg)](https://phpackages.com/packages/gbksoft-yii2-tokens)
```

###  Alternatives

[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)[lowbase/yii2-user

Yii2 user module

131.5k2](/packages/lowbase-yii2-user)[kakadu-dev/yii2-jwt-auth

Extension provide JWT auth for Yii2

105.8k](/packages/kakadu-dev-yii2-jwt-auth)

PHPackages © 2026

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