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

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

agielks/yii2-jwt
================

JWT based on Icobucci version 4.1

1.0.0(3y ago)03.2k—0%BSD-3-ClausePHPPHP &gt;=8.0

Since Jul 13Pushed 3y ago1 watchersCompare

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

READMEChangelogDependencies (3)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) (requires PHP 8.0+). It includes basic HTTP authentication support.

[![Latest Stable Version](https://camo.githubusercontent.com/dde249562849982fec64346ba60722fe7b84fbdffd52d3b01520ec1203d2e81d/687474703a2f2f706f7365722e707567782e6f72672f616769656c6b732f796969322d6a77742f76)](https://packagist.org/packages/agielks/yii2-jwt)[![Total Downloads](https://camo.githubusercontent.com/1982b3cacc779adefd5828e66da1fef4d8565f576c72374e58a81c903a790047/687474703a2f2f706f7365722e707567782e6f72672f616769656c6b732f796969322d6a77742f646f776e6c6f616473)](https://packagist.org/packages/agielks/yii2-jwt)[![Latest Unstable Version](https://camo.githubusercontent.com/15af27a12ae7f457a71c748d918ccc3f9b0943c5d6cd02319a2d101f6a0a5bb2/687474703a2f2f706f7365722e707567782e6f72672f616769656c6b732f796969322d6a77742f762f756e737461626c65)](https://packagist.org/packages/agielks/yii2-jwt)[![License](https://camo.githubusercontent.com/2452200bafbe58562f607a6637d7ec40d11e9992f9804308a733744740c06e5d/687474703a2f2f706f7365722e707567782e6f72672f616769656c6b732f796969322d6a77742f6c6963656e7365)](https://packagist.org/packages/agielks/yii2-jwt)[![PHP Version Require](https://camo.githubusercontent.com/43a6ee2729ba1278ebe901b313b1b8efbfb58e8f5e07f035e70225dbd7f5c887/687474703a2f2f706f7365722e707567782e6f72672f616769656c6b732f796969322d6a77742f726571756972652f706870)](https://packagist.org/packages/agielks/yii2-jwt)

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

[](#table-of-contents)

1. [Installation](#installation)
2. [Dependencies](#dependencies)
3. [Basic usage](#basicusage)
    1. [Create token](#basicusage-create)
    2. [Parse token from string](#basicusage-parse)
    3. [Validate token](#basicusage-validate)
4. [Login Example](#login-example)

Instalation
-----------

[](#instalation)

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

```
composer require agielks/yii2-jwt ~1.0
```

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

```
"agielks/yii2-jwt": "~1.0"

```

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

[](#dependencies)

- PHP 8.0+
- OpenSSL Extension
- Sodium Extension
- [lcobucci/jwt 4.1](https://github.com/lcobucci/jwt/tree/4.1)

Basic Usage
-----------

[](#basic-usage)

Add `jwt` component to your configuration file,

```
'components' => [
    'jwt' => [
        'class' => \agielks\yii2\jwt\Jwt::class,
        // 'singer' => new \Lcobucci\JWT\Signer\Hmac\Sha256(),
        'signer' => 'HS256',
        // 'key' => \Lcobucci\JWT\Signer\Key\InMemory::plainText('my-key'),
        'key' => 'my-key', ,
    ],
],
```

**Important: If you don't provide the signer and the key it will use unsecured signer**

Configure the `authenticator` behavior as follows.

```
namespace app\controllers;

class SiteController extends \yii\rest\Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => \agielks\yii2\jwt\JwtBearerAuth::class,
        ];

        return $behaviors;
    }
}
```

Also you can use it with `CompositeAuth` reffer to a [doc](http://www.yiiframework.com/doc-2.0/guide-rest-authentication.html).

Create Token
------------

[](#create-token)

```
/* @var $jwt \agielks\yii2\jwt\Jwt */

$now = new DateTimeImmutable();
$jwt = Yii::$app->get('jwt');

$token = $jwt
    ->builder()
    // Configures the issuer (iss claim)
    ->issuedBy('http://example.com')
    // Configures the audience (aud claim)
    ->permittedFor('http://example.org')
    // Configures the id (jti claim)
    ->identifiedBy('62cbfaca6bf7e')
    // Configures the time that the token was issue (iat claim)
    ->issuedAt($now)
    // Configures the time that the token can be used (nbf claim) required for StrictValidAt constraint
    ->canOnlyBeUsedAfter($now)
    // Configures the expiration time of the token (exp claim)
    ->expiresAt($now->modify('+1 hour'))
    // Configures a new claim, called "uid"
    ->withClaim('uid', '62cbfaca6bf7e')
    // Configures a new header, called "foo"
    ->withHeader('foo', 'bar')
    // Builds a new token
    ->getToken($jwt->signer(), $jwt->key());

// Retrieves all headers
$token->headers()->all();

// Retrives typ from headers
$token->headers()->get('typ');

// Print typ from headers
print_r($token->headers()->get('typ'));

// Retrieves all claims
$token->claims()->all();

// Retrieves jti from claims
$token->claims()->get('jti');

// Print jti from claims
print_r($token->claims()->get('jti'));
```

Parse Token From String
-----------------------

[](#parse-token-from-string)

```
/* @var $jwt \agielks\yii2\jwt\Jwt */

$now = new DateTimeImmutable();
$jwt = Yii::$app->get('jwt');

$token = $jwt
    ->builder()
    // ...
    ->expiresAt($now->modify('+1 hour'))
    ->getToken($jwt->signer(), $jwt->key())
    ->toString();

// Parse without validation
$data = $jwt->config()->parser()->parse($token);

// Parse with validation
$data = $jwt->load($token);

// Print all headers
print_r($data->headers()->all());

// Print all claims
print_r($data->claims()->all());

// Validate token
var_dump($data->isExpired($now));
var_dump($data->isExpired($now->modify('+2 hour')));
```

Validate Token
--------------

[](#validate-token)

You can configure your own validation with simple configuration in your component

```
use \agielks\yii2\jwt\Jwt;
use \Lcobucci\JWT\Signer\Hmac\Sha256;
use \Lcobucci\JWT\Signer\Key\InMemory;
use \Lcobucci\JWT\Validation\Constraint\LooseValidAt;
use \Lcobucci\JWT\Validation\Constraint\SignedWith;
use \Lcobucci\JWT\Validation\Constraint\IdentifiedBy;
use \Lcobucci\Clock\SystemClock;

'components' => [
    'jwt' => [
        'class' => Jwt::class,
        'signer' => new Sha256(),
        'key'   => InMemory::plainText('my-key'),
        'constraints' => [
            new LooseValidAt(SystemClock::fromSystemTimezone()),
            new SignedWith(
                new Sha256(),
                InMemory::plainText('my-key')
            ),
            new IdentifiedBy('my-identity'),
        ],
    ],
],
```

Login Example
-------------

[](#login-example)

### Basic scheme

[](#basic-scheme)

1. Client send credentials. For example, login + password
2. App validate the credentials
3. If credentials is valid client receive token
4. Client store token for the future requests

### Step by step usage

[](#step-by-step-usage)

1. Install component

```
composer require agielks/yii2-jwt ~1.0
```

2. Update your components configuration

```
'components' => [
    // other components here...
    'jwt' => [
        'class' => \agielks\yii2\jwt\Jwt::class,
        // 'singer' => new \Lcobucci\JWT\Signer\Hmac\Sha256(),
        'signer' => 'HS256',
        // 'key' => \Lcobucci\JWT\Signer\Key\InMemory::plainText('my-key'),
        'key' => 'my-key', ,
    ],
    // ...
],
```

3. Change method `User::findIdentityByAccessToken()`

```
/**
 * {@inheritdoc}
 * @param \Lcobucci\JWT\Token $token
 */
public static function findIdentityByAccessToken($token, $type = null)
{
   return static::findOne(['id' => $token->claims()->get('uid')]);
}
```

If you want to use auth\_key as key, update method as follows

```
/**
 * {@inheritdoc}
 * @param \Lcobucci\JWT\Token $token
 */
public static function findIdentityByAccessToken($token, $type = null)
{
   return static::findOne(['auth_key' => $token->claims()->get('auth_key')]);
}
```

4. Create controller

```
use agielks\yii2\jwt\JwtBearerAuth;
// Use your own login form
use common\models\LoginForm;
use DateTimeImmutable;
use Yii;
use yii\base\InvalidConfigException;
use yii\filters\Cors;
use yii\rest\Controller;
use yii\web\Response;

/**
 * Class SiteController
 */
class SiteController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        $behaviors['corsFilter'] = ['class' => Cors::class];
        $behaviors['authenticator'] = [
            'class' => JwtBearerAuth::class,
            'optional' => [
                'login',
            ],
        ];

        return $behaviors;
    }

    /**
     * {@inheritdoc}
     */
    protected function verbs()
    {
        return [
            'login' => ['OPTIONS', 'POST'],
        ];
    }

    /**
     * @return array|LoginForm
     * @throws InvalidConfigException
     */
    public function actionLogin()
    {
        $model = new LoginForm();

        if ($model->load(Yii::$app->getRequest()->getBodyParams(), '') && $model->login()) {
            /* @var $jwt \agielks\yii2\jwt\Jwt */

            $now = new DateTimeImmutable();
            $jwt = Yii::$app->get('jwt');
            $user = $model->getUser();

            return $jwt
                ->builder()
                // Configures the issuer (iss claim)
                ->issuedBy('http://example.com')
                // Configures the audience (aud claim)
                ->permittedFor('http://example.org')
                // Configures the id (jti claim)
                ->identifiedBy($user->id)
                // Configures the time that the token was issue (iat claim)
                ->issuedAt($now)
                // Configures the time that the token can be used (nbf claim)
                ->canOnlyBeUsedAfter($now)
                // Configures the expiration time of the token (exp claim)
                ->expiresAt($now->modify('+1 hour'))
                // Configures a new claim, called "uid"
                ->withClaim('uid', $user->id)
                // Configures a new claim, called "auth_key"
                ->withClaim('auth_key', $user->auth_key)
                // Returns a signed token to be used
                ->getToken($jwt->signer(), $jwt->key())
                // Convert token to string
                ->toString();
        }

        $model->validate();
        return $model;
    }

    /**
     * Test authentication
     */
    public function actionTest()
    {
        return ['auth' => 'success'];
    }
}
```

###  Health Score

27

—

LowBetter than 52% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity20

Limited adoption so far

Community4

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

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

1348d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/47511429?v=4)[Agiel K. Saputra](/maintainers/agielks)[@agielks](https://github.com/agielks)

---

Tags

jwtyii2yii 2

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[sizeg/yii2-jwt

JWT based on Icobucci

196984.3k5](/packages/sizeg-yii2-jwt)[bizley/jwt

JWT integration for Yii 2

67409.2k2](/packages/bizley-jwt)[kakadu-dev/yii2-jwt-auth

Extension provide JWT auth for Yii2

105.8k](/packages/kakadu-dev-yii2-jwt-auth)[vova07/yii2-rbac-module

The RBAC module for Yii framework.

191.2k2](/packages/vova07-yii2-rbac-module)

PHPackages © 2026

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