PHPackages                             astrotechlabs/yii2-jwt-tools - 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. astrotechlabs/yii2-jwt-tools

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

astrotechlabs/yii2-jwt-tools
============================

An easy way to configure JWT authentication and validation on Yii Framework 2 Projects

1.0.9(9mo ago)332.5k9[2 issues](https://github.com/AstrotechLabs/yii2-jwt-tools/issues)MITPHPPHP &gt;=8CI failing

Since May 10Pushed 9mo ago3 watchersCompare

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

READMEChangelog (5)Dependencies (5)Versions (12)Used By (0)

JWT Tools to Yii Framework 2
============================

[](#jwt-tools-to-yii-framework-2)

[![GitHub](https://camo.githubusercontent.com/120a3f240d870a573916ff8c8225a63f8f392e2a58e6d5699fdd45f91dbe25ad/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f646572736f6e73656e612f796969322d6a77742d746f6f6c73)](https://camo.githubusercontent.com/120a3f240d870a573916ff8c8225a63f8f392e2a58e6d5699fdd45f91dbe25ad/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f646572736f6e73656e612f796969322d6a77742d746f6f6c73) [![GitHub repo size](https://camo.githubusercontent.com/6e0a03084394e54dfe0e8d5d6c19fee85c491c8ed944c4bb804e9556e133ce29/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f7265706f2d73697a652f646572736f6e73656e612f796969322d6a77742d746f6f6c73)](https://camo.githubusercontent.com/6e0a03084394e54dfe0e8d5d6c19fee85c491c8ed944c4bb804e9556e133ce29/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f7265706f2d73697a652f646572736f6e73656e612f796969322d6a77742d746f6f6c73) [![Packagist Stars](https://camo.githubusercontent.com/2a9e78b74567c71868f361fb5e4cdf2ce9257a46ec09b05f55253dfc7ec97881/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f73746172732f646572736f6e73656e612f796969322d6a77742d746f6f6c73)](https://camo.githubusercontent.com/2a9e78b74567c71868f361fb5e4cdf2ce9257a46ec09b05f55253dfc7ec97881/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f73746172732f646572736f6e73656e612f796969322d6a77742d746f6f6c73) [![Packagist PHP Version Support (specify version)](https://camo.githubusercontent.com/a3fcb755379b2f2bc2d493cd867a5cc7829050c796f0ed6275f10ece3d633cbd/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f646572736f6e73656e612f796969322d6a77742d746f6f6c732f312e302e30)](https://camo.githubusercontent.com/a3fcb755379b2f2bc2d493cd867a5cc7829050c796f0ed6275f10ece3d633cbd/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f646572736f6e73656e612f796969322d6a77742d746f6f6c732f312e302e30) [![Packagist Downloads](https://camo.githubusercontent.com/be58f930f9420246b230b5041a69dad3ef274ec3663429f794ea2ff537445ac2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646d2f646572736f6e73656e612f796969322d6a77742d746f6f6c73)](https://camo.githubusercontent.com/be58f930f9420246b230b5041a69dad3ef274ec3663429f794ea2ff537445ac2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646d2f646572736f6e73656e612f796969322d6a77742d746f6f6c73)

JWT Tools is a toolbox that will help you to configure authentication with [JWT](http://jwt.io/) token. Not only authentication but also signature validation, the famous secret key.

My biggest motivation to do this was because I didn't see a easy way to setup a simple JWT Validation with some helper functions. I always needed copy and past whole the code to a new project.

Follow the steps below to install and setup in your project.

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

[](#installation)

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

To install, either run:

```
$ php composer.phar require dersonsena/yii2-jwt-tools
```

or add

```
"dersonsena/yii2-jwt-tools": "^1.0"

```

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

Usage
-----

[](#usage)

### Configuration File

[](#configuration-file)

Let's guarantee somes application settings are correct. Open your `config/web.php` and setup such as:

```
'components' => [
    // ...
    'request' => [
        'enableCookieValidation' => false,
    ],
    'user' => [
        'identityClass' => 'app\models\User',
        'enableAutoLogin' => false,
        'enableSession' => false,
        'loginUrl' => null
    ],
    // ...
```

### Controller

[](#controller)

In your controller class, register the [JWTSignatureBehavior](./src/JWTSignatureBehavior.php) and [HttpBearerAuth](https://www.yiiframework.com/doc/api/2.0/yii-filters-auth-httpbearerauth) behaviors in `behaviors()` method, such as below:

```
use yii\rest\Controller;

class YourCuteController extends Controller
{
    public function behaviors()
    {
        $behaviors = parent::behaviors();

        $behaviors['jwtValidator'] = [
            'class' => JWTSignatureBehavior::class,
            'secretKey' => Yii::$app->params['jwt']['secret'],
            'except' => ['login'] // it's doesn't run in login action
        ];

        $behaviors['authenticator'] = [
            'class' => HttpBearerAuth::class,
            'except' => ['login'] // it's doesn't run in login action
        ];

        return $behaviors;
    }
}
```

> **NOTE:** in this examples I used `Yii::$app->params['jwt']['secret']` to store my JWT Secret Key, but, I like a lot of the .env files and this information could be stored there

The `JWTSignatureBehavior` will validate the JWT token sent by `Authorization` HTTP Header. If there are some problem with your token this one it will throw one of Exceptions below:

- [UnauthorizedHttpException](https://www.yiiframework.com/doc/api/2.0/yii-web-unauthorizedhttpexception) with message `Your request was made without an authorization token.` if HTTP Header doesn't exist or token is empty or null.
- [UnauthorizedHttpException](https://www.yiiframework.com/doc/api/2.0/yii-web-unauthorizedhttpexception) with message `Authentication token is expired.` if token is out of due.
- [UnauthorizedHttpException](https://www.yiiframework.com/doc/api/2.0/yii-web-unauthorizedhttpexception) with message `The token signature is invalid.` if the token signature is invalid.

If for some reason you need to change the HTTP Header name (to be honest I can't see this scenario) you can change this one setting up the `headerName` property, such as below:

```
class YourCuteController extends Controller
{
    // ...
    public function behaviors()
    {
        $behaviors['jwtValidator'] = [
            'class' => JWTSignatureBehavior::class,
            'secretKey' => Yii::$app->params['jwt']['secret'],
            'headerName' => 'Auth'
        ];
    }
    // ...
}
```

In your login action you need to create a JWT Token to send your response. It's very easy create a token, see below:

```
class YourCuteController extends Controller
{
    // ...
    public function behaviors()
    {
        $behaviors['jwtValidator'] = [
            'class' => JWTSignatureBehavior::class,
            'secretKey' => Yii::$app->params['jwt']['secret'],
            'headerName' => 'Auth'
        ];
    }

    public function actionLogin()
    {
        // validation stuff
        // find user

        $token = JWTTools::build(Yii::$app->params['jwt']['secret'])
            ->withModel($user, ['name', 'email', 'group'])
            ->getJWT();

        return ['success' => true, 'token' => $token];
    }
    // ...
}
```

### Model Identity Class

[](#model-identity-class)

At this point we know that the token is valid and we can decode this one to authenticate user.

I'm using here `app/models/User` as my User Identity, so, let's implement the `findIdentityByAccessToken()` method of the [IdentityInterface](https://www.yiiframework.com/doc/api/2.0/yii-web-identityinterface) interface:

```
namespace app\models;

use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

class User extends ActiveRecord implements IdentityInterface
{
    // ...
    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    public function getId()
    {
        return $this->id;
    }

    public function getAuthKey()
    {
        // we don't need to implement this method
    }

    public function validateAuthKey($authKey)
    {
        // we don't need to implement this method
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        $decodedToken = JWTTools::build(Yii::$app->params['jwt']['secret'])
            ->decodeToken($token);

        return static::findOne(['id' => $decodedToken->sub]);
    }
}
```

If all ok, at this point you're able to authenticate with a valid JWT Token.

Demos
-----

[](#demos)

### Generating a token

[](#generating-a-token)

You can use the [JWTTools](./src/JWTTools.php) methods to make specific things in your project. See some examples below:

```
use AstrotechLabs\JWTTools\JWTTools;

$jwtTools = JWTTools::build('my-secret-key');

$token = $jwtTools->getJWT();
$payload = $jwtTools->getPayload()->getData();

var_dump($token);
print_r($payload);
```

This code will be return something like:

```
string(248) "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImtpZCI6ImJlMTgzOTQ4YjJmNjkzZSJ9.eyJzdWIiOiJiZTE4Mzk0OGIyZjY5M2UiLCJpc3MiOiIiLCJhdWQiOiIiLCJpYXQiOjE1ODkxMzEzNjIsImV4cCI6MTU4OTEzNDk2MiwianRpIjoiNTM4NTRiMGQ5MzFkMGVkIn0.-JDBkID1oJ7anC_JLg68AJxbKGK-5ubA83zZlDZYYso"

Array
(
    [sub] => 9c65241853de774
    [iss] =>
    [aud] =>
    [iat] => 1589129672
    [exp] => 1589133272
    [jti] => a0a98e2364d2721
)

```

> **NOTE:** the `->getPayload()` returns an instance of the [JWTPayload](./src/JWTPayload.php).

### Generating Token with an Active Record

[](#generating-token-with-an-active-record)

You can insert the active record attributes in your payload using `withModel()` method, like this:

```
use AstrotechLabs\JWTTools\JWTTools;

$user = app\models\User::findOne(2);

$payload = JWTTools::build('my-secret-key');
    ->withModel($user, ['id', 'name', 'email'])
    ->getPayload()
    ->getData();

print_r($payload);
```

This code will be return something like:

```
Array
(
    [sub] => 10
    [aud] =>
    [iat] => 1589130028
    [exp] => 1589133628
    [jti] => 7aba5b7666d7868
    [id] => 10                     Kilderson Sena       email@email.com.br getPrimaryKey()` value, following the [RFC7519](https://tools.ietf.org/html/rfc7519#section-4.1) instructions.

### Changing JWT Properties

[](#changing-jwt-properties)

You can change the JWT Properties (such as `iss`, `aud` etc) adding an array in second method parameter, as below:

```
use AstrotechLabs\JWTTools\JWTTools;

$payload = JWTTools::build('my-secret-key', [
    'algorithm' => 'ES256',
    'expiration' => 1589069866,  // 'yourdomain.com',
    'aud' => 'yourdomain.com',
]);
```

Authors
-------

[](#authors)

- [Kilderson Sena](https://github.com/dersonsena) - Initial work - [Yii Academy](https://www.yiiacademy.com.br)

See also the list of [contributors](https://github.com/dersonsena/yii2-jwt-tools/contributors) who participated in this project.

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

[](#contributing)

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

Licence
-------

[](#licence)

This package is released under the [MIT](https://choosealicense.com/licenses/mit/) License. See the bundled [LICENSE](./LICENSE) for details.

###  Health Score

45

—

FairBetter than 91% of packages

Maintenance56

Moderate activity, may be stable

Popularity32

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 97.1% 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 ~217 days

Recently: every ~351 days

Total

10

Last Release

284d ago

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

1.0.5PHP &gt;=8

### Community

Maintainers

![](https://www.gravatar.com/avatar/61bcbe92662af44dfdd25b210c73e52956e381536edb62ddfae95810e3333e31?d=identicon)[astrotechdevs](/maintainers/astrotechdevs)

---

Top Contributors

[![dersonsena](https://avatars.githubusercontent.com/u/9482515?v=4)](https://github.com/dersonsena "dersonsena (34 commits)")[![almirb](https://avatars.githubusercontent.com/u/1752962?v=4)](https://github.com/almirb "almirb (1 commits)")

---

Tags

yii2yii2-auth-jwtyii2-authenticationyii2-extensionyii2-frameworkyii2-jwtyii2-jwt-authyii2-securiyyii2yii2-extensionyii2-frameworkyii2-authenticationyii2-jwtyii2-jwt-authyii2-securityyii2-jwt-tools

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/astrotechlabs-yii2-jwt-tools/health.svg)

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

###  Alternatives

[craftcms/cms

Craft CMS

3.6k3.6M2.9k](/packages/craftcms-cms)[edvlerblog/yii2-adldap-module

yii2 Active Directory implementation (wrapper for Adldap2)

49231.2k](/packages/edvlerblog-yii2-adldap-module)[ellaisys/aws-cognito

AWS Cognito package that allows Auth and other related features using the AWS SDK for PHP

121242.9k1](/packages/ellaisys-aws-cognito)[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)
