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

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

davidxu/yii2-jwt
================

A JWT extension based on Icobucci

1.0.0(3y ago)07MITPHPPHP ^8.0

Since Feb 28Pushed 3y ago1 watchersCompare

[ Source](https://github.com/davidxuuts/yii2-jwt)[ Packagist](https://packagist.org/packages/davidxu/yii2-jwt)[ RSS](/packages/davidxu-yii2-jwt/feed)WikiDiscussions master Synced yesterday

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

Yii2 JWT
========

[](#yii2-jwt)

This extension provides the [JWT](https://github.com/lcobucci/jwt) integration for the [Yii framework 2.0](http://www.yiiframework.com).

Table of contents
-----------------

[](#table-of-contents)

1. [Installation](#installation)
2. [Dependencies](#dependencies)
3. [Basic usage](#basicusage)
    1. [Generating public and private keys](#generating-public-and-private-keys)
    2. [Use as a Yii component](#use-as-a-yii-component)
    3. [Use as a Yii params](#use-as-a-yii-params)
    4. [Creating](#basicusage-creating)
    5. [Parsing from strings](#basicusage-parsing)
    6. [Validating](#basicusage-validating)
4. [Yii2 advanced template example](#yii2advanced-example)

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

[](#installation)

Package is available on [Packagist](https://packagist.org/packages/davidxu/yii2-jwt), you can install it using [Composer](http://getcomposer.org).

```
composer require davidxu/yii2-jwt
```

Dependencies
------------

[](#dependencies)

- PHP 8.0+
- OpenSSL Extension

Basic usage
-----------

[](#basic-usage)

### 1. Generating public and private keys

[](#1-generating-public-and-private-keys)

The public/private key pair is used to sign and verify JWTs transmitted. To generate the private key run this command on the terminal:

```
openssl genrsa -out private.key 2048
```

If you want to provide a passphrase for your private key run this command instead:

```
openssl genrsa -aes128 -passout pass:_passphrase_ -out private.key 2048
```

then extract the public key from the private key:

```
openssl rsa -in private.key -pubout -out public.key
```

or use your passphrase if provided on private key generation:

```
openssl rsa -in private.key -passin pass:_passphrase_ -pubout -out public.key
```

The private key must be kept secret (i.e. out of the web-root of the authorization server).

### 2.1 Use as a Yii component

[](#21-use-as-a-yii-component)

Add `jwt` component to your configuration file,

```
'components' => [
    'jwt' => [
        'class' => \davidxu\jwt\Jwt::class,
        'privateKey' => __DIR__ . '/../private.key',
        'publicKey' => __DIR__ . '/../public.key',
        // A date/time string. Valid formats are explained in
        // [Date and Time Formats](https://secure.php.net/manual/en/datetime.formats.php)
        'expire_time' => '+2 hour'
    ],
],
```

### 2.2 Use as a Yii params

[](#22-use-as-a-yii-params)

Add following params in `params.php`

```
return [
    //...
    'jwt' => [
        'privateKey' => __DIR__ . '/../private.key',
        'publicKey' => __DIR__ . '/../public.key',
        'expire_time' => '+2 hour'
    ],
    //...
];
```

Configure the `authenticator` behavior as follows.

```
namespace app\controllers;

class ExampleController extends \yii\rest\Controller
{

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => CompositeAuth::class,
            'authMethods' => [
                [
                    'class' => HttpBearerAuth::class,
                ],
            ]
        ];
        return $behaviors;
    }
}
```

### 3. Creating

[](#3-creating)

Just use `getToken` to create/issue a new JWT token:

```
$jwt = new davidxu\jwt\Jwt();
// OR
// $jwt = Yii::$app->jwt;
$token = $jwt->getToken([
    'uid' => 12345,
    'app_id' => Yii::$app->id,
]);

echo $token->claims()->get('uid'); // will print "12345"
echo $token->toString();
```

### Parsing from strings

[](#parsing-from-strings)

Use `parseToken` to parse a token from a JWT string (using the previous token as example):

```
$jwt = new davidxu\jwt\Jwt();
// OR
// $jwt = Yii::$app->jwt;
$token = $jwt->parseToken($token);
echo $token->claims()->get('uid'); // will print "12345"
```

### Validating

[](#validating)

We can easily validate if the token is valid (using the previous token as example):

```
$jwt = new davidxu\jwt\Jwt();
// OR
// $jwt = Yii::$app->jwt;
$valid = $jwt->validateToken($token, true, [
    'app_id' => Yii::$app->id,
    ], 'uid'); // return 12345(uid)
```

Yii2 advanced template example
------------------------------

[](#yii2-advanced-template-example)

### Change method `common\models\User::findIdentityByAccessToken()`

[](#change-method-commonmodelsuserfindidentitybyaccesstoken)

```
public static function findIdentityByAccessToken($token, $type = null): ?Member
{
    // use yii2 components
    $jwt = Yii::$app->jwt;
    // use yii2 params
    $jwt = new \davidxu\jwt\Jwt();
    $jwt->privateKey = Yii::$app->params['jwt']['privateKey'];
    $jwt->publicKey = Yii::$app->params['jwt']['publicKey'];
    $jwt->expire_time = '+2 hour';
    return Member::findOne($jwt->validateToken($jwt->parseToken($token)));
}
```

###  Health Score

22

—

LowBetter than 21% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity4

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 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

Unknown

Total

1

Last Release

1222d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/59e94d6d1e147e3ed702e4f3dcbeb3eca9a9b228ad58dc014530212e0a3f3ba5?d=identicon)[davidxuuts](/maintainers/davidxuuts)

---

Top Contributors

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

---

Tags

jwtyii2extensionyii2-jwt

### Embed Badge

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

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

###  Alternatives

[sizeg/yii2-jwt

JWT based on Icobucci

1951.1M7](/packages/sizeg-yii2-jwt)[bizley/jwt

JWT integration for Yii 2

69478.8k2](/packages/bizley-jwt)[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)
