PHPackages                             kakadu-dev/yii2-jwt-auth - 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. kakadu-dev/yii2-jwt-auth

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

kakadu-dev/yii2-jwt-auth
========================

Extension provide JWT auth for Yii2

2.0(6y ago)105.8k6[1 issues](https://github.com/kakadu-dev/yii2-jwt-auth/issues)MITPHPPHP &gt;=7.1CI failing

Since Nov 23Pushed 6y ago3 watchersCompare

[ Source](https://github.com/kakadu-dev/yii2-jwt-auth)[ Packagist](https://packagist.org/packages/kakadu-dev/yii2-jwt-auth)[ RSS](/packages/kakadu-dev-yii2-jwt-auth/feed)WikiDiscussions master Synced 3w ago

READMEChangelog (4)Dependencies (2)Versions (6)Used By (0)

yii2-jwt-auth
=============

[](#yii2-jwt-auth)

Yii2 JWT Auth

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

[](#installation)

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

Either run

```
php composer.phar require --prefer-dist kakadu-dev/yii2-jwt-auth "@dev"
```

or add

```
"kakadu-dev/yii2-jwt-auth": "@dev"

```

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

Usage
-----

[](#usage)

Once the extension is installed, simply use it in your code by:

Add this package migration namespace, to you console config (console/config/main.php):

```
return [
    'components' => [
        'migrate' => [
            'class'               => yii\console\controllers\MigrateController::class,
            // set false if you use namespaces
            'migrationPath'       => '@console/migrations',
            'migrationNamespaces' => [
                // ...
                'Kakadu\Yii2JwtAuth\migrations',
            ],
        ],
    ],
];
```

Configure api tokens component (e.g. common/config/main.php):

```
return [
    'components' => [
        'apiTokens' => [
            'class'           => \Kakadu\Yii2JwtAuth\ApiTokenService::class,
            'secretKey'       => '', // set in main-local.php or yii-params.domainSecretKey
            'issuer'          => 'you-domain-name', // or yii-params.domain
            'audience'        => ['you-domain-name', 'second-domain-name'], // or yii-params.domain
            'audienceSecrets' => [
                'you-domain-name'    => '', // or yii-params.domainSecretKey
                'second-domain-name' => '', // or yii-params.secondDomainSecretKey
            ],
            'seamlessLogin'   => false,
        ],
    ],
];
```

All values in *secretKey*, *issuer*, *audience*, *audienceSecrets* which contain *yii-params.param-name* will be converted to Yii::$app-&gt;params\['param-name'\]

TBD: add example for `yii-params.*` config (e.g. for `audienceSecrets`).

Now, after user registration, create JWT tokens and add their in response headers. Also add an action to update tokens.
E.g.:

```
class AuthController extends yii\rest\Controller
{
    public function actionSignUp()
    {
        // After create user $newUser
        // Same actions for login url
        $tokens = \Yii::$app->apiTokens->create($newUser->id, ['someField' => 'someValue']);

        \Kakadu\Yii2JwtAuth\JwtBearerAuth::addJwtToHeader(\Yii::$app->response, $tokens);
    }

    public function actionSignIn()
    {
        // After verify user login and password

        $tokens = \Yii::$app->apiTokens->create($user->id, ['someField' => 'someValue']);

        \Kakadu\Yii2JwtAuth\JwtBearerAuth::addJwtToHeader(\Yii::$app->response, $tokens);
    }

    /**
     * Autologin, if access token expired and refresh token not expired.
     * This action needed only if 'seamlessLogin' set to false.
     */
    public function actionRefreshTokens()
    {
        // Get from post or headers or ...
        $accessToken = Yii::$app->request->post('access_token');
        $refreshToken = Yii::$app->request->post('refresh_token');

        // Convert to jwt token model
        $jwtAccessToken  = \Yii::$app->apiTokens->getJwtToken($accessToken);
        $jwtRefreshToken = \Yii::$app->apiTokens->getJwtToken($refreshToken);

        // Renew
        $newTokens = \Yii::$app->apiTokens->renewJwtToken($jwtAccessToken, $jwtRefreshToken);

        \Kakadu\Yii2JwtAuth\JwtBearerAuth::addJwtToHeader(\Yii::$app->response, $newTokens);
    }
}
```

or use renew tokens action:

```
use Kakadu\Yii2JwtAuth\RefreshTokensAction;

class AuthController extends yii\rest\Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors(): array
    {
        return ArrayHelper::merge(parent::behaviors(), [
            'authenticator' => [
                'class'  => JwtBearerAuth::class,
                'except' => ['renew-token'],
            ],
            'access'        => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow'   => true,
                        'actions' => ['renew-token'],
                        'roles'   => ['?'],
                    ],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions(): array
    {
        return ArrayHelper::merge(parent::actions(), [
            'renew-token' => RefreshTokensAction::class,
        ]);
    }
}
```

And finally add Jwt Auth to secure controller:

```
class SecureController extends yii\rest\Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors(): array
    {
        return ArrayHelper::merge(parent::behaviors(), [
            'authenticator' => [
                'class' => \Kakadu\Yii2JwtAuth\JwtBearerAuth::class,
            ],
            'access'        => [
                'class' => AccessControl::class,
                'rules' => [
                   ...
                ],
            ],
        ]);
    }
}
```

**Procedure:**

- seamlessLogin is false

    1. Register, get access and refresh token and save their on client side.
    2. Use only access token for request to security endpoint.
    3. After access token expired, you get 401 Unauthorized exception.
    4. *Use expire access and not expire refresh token to get new tokens.* (/refresh-token url)
    5. If refresh token expire, go to sign in
- seamlessLogin is true

    1. Register, get access and refresh token and save their on client side.
    2. Use only access token for request to security endpoint.
    3. After access token expired, you get 401 Unauthorized exception.
    4. *Repeat request use expire access and not expire refresh token to get new tokens.* (/same url)
    5. If refresh token expire, go to sign in.

That's all. Check it.

###  Health Score

33

—

LowBetter than 72% of packages

Maintenance18

Infrequent updates — may be unmaintained

Popularity27

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 69.2% 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 ~136 days

Total

4

Last Release

2362d ago

Major Versions

1.2 → 2.02020-01-08

### Community

Maintainers

![](https://www.gravatar.com/avatar/977a098fd4018ff88b9523d52b5a438a6d1292e8f8c7316779760b6ada2ebc0c?d=identicon)[kakadudev](/maintainers/kakadudev)

---

Top Contributors

[![MatthewPattell](https://avatars.githubusercontent.com/u/10459911?v=4)](https://github.com/MatthewPattell "MatthewPattell (18 commits)")[![k-timoshenko](https://avatars.githubusercontent.com/u/3259675?v=4)](https://github.com/k-timoshenko "k-timoshenko (8 commits)")

---

Tags

apiauthenticationjwtrestyii2jwtapiauthyii2extension

### Embed Badge

![Health badge](/badges/kakadu-dev-yii2-jwt-auth/health.svg)

```
[![Health](https://phpackages.com/badges/kakadu-dev-yii2-jwt-auth/health.svg)](https://phpackages.com/packages/kakadu-dev-yii2-jwt-auth)
```

###  Alternatives

[benbjurstrom/cognito-jwt-guard

A laravel auth guard for JSON Web Tokens issued by Amazon AWS Cognito

1113.1k](/packages/benbjurstrom-cognito-jwt-guard)

PHPackages © 2026

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