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

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

bizley/jwt
==========

JWT integration for Yii 2

4.1.2(1y ago)67425.3k↓13.8%10[2 PRs](https://github.com/bizley/yii2-jwt/pulls)2Apache-2.0PHPPHP &gt;=8.1CI passing

Since Mar 28Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/bizley/yii2-jwt)[ Packagist](https://packagist.org/packages/bizley/jwt)[ GitHub Sponsors](https://github.com/bizley)[ RSS](/packages/bizley-jwt/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (7)Versions (24)Used By (2)

[![Latest Stable Version](https://camo.githubusercontent.com/25c2297058053e8af62cbf631e6f496d06bc597d134a818912c403d2e7b5f3f9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f62697a6c65792f6a77742e737667)](https://camo.githubusercontent.com/25c2297058053e8af62cbf631e6f496d06bc597d134a818912c403d2e7b5f3f9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f62697a6c65792f6a77742e737667)[![Total Downloads](https://camo.githubusercontent.com/507de88d06949258ca5dc8396b9dded8014fbb55e139043b081ad9f61681ba18/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f62697a6c65792f6a77742e737667)](https://packagist.org/packages/bizley/jwt)[![License](https://camo.githubusercontent.com/3c2524bd9a965762231ae34bd82a306e230d7579647b34f3a2d9a32c3a1f9c11/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f62697a6c65792f6a77742e737667)](https://camo.githubusercontent.com/3c2524bd9a965762231ae34bd82a306e230d7579647b34f3a2d9a32c3a1f9c11/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f62697a6c65792f6a77742e737667)[![Mutation testing badge](https://camo.githubusercontent.com/fff4f01e1142a07d5870fd800c5cbfbed74e370bb4bfd0d4136c2e6558eac450/68747470733a2f2f696d672e736869656c64732e696f2f656e64706f696e743f7374796c653d666c61742675726c3d687474707325334125324625324662616467652d6170692e737472796b65722d6d757461746f722e696f2532466769746875622e636f6d25324662697a6c6579253246796969322d6a77742532466d6173746572)](https://dashboard.stryker-mutator.io/reports/github.com/bizley/yii2-jwt/master)

JWT Integration For Yii 2
=========================

[](#jwt-integration-for-yii-2)

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

> This is a fork of [sizeg/yii2-jwt](https://github.com/sizeg/yii2-jwt) package

Available versions
==================

[](#available-versions)

bizley/yii2-jwtlcobucci/jwtphp`^4.0``^5.0``>=8.1``^3.0``^4.0``>=7.4``^2.0``^3.0``>=7.1`See [lcobucci/jwt](https://github.com/lcobucci/jwt) repo for details about the version.

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

[](#installation)

Add the package to your `composer.json`:

```
{
    "require": {
        "bizley/jwt": "^4.0"
    }
}
```

and run `composer update` or alternatively run `composer require bizley/jwt:^4.0`

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

[](#basic-usage)

Add `jwt` component to your configuration file.

If your application is both the issuer and the consumer of JWT (the common case, a.k.a. Standard version) use `bizley\jwt\Jwt` component:

```
[
    'components' => [
        'jwt' => [
            'class' => \bizley\jwt\Jwt::class,
            'signer' => ... // Signer ID, or signer object, or signer configuration, see "Available signers" below
            'signingKey' => ... // Secret key string or path to the signing key file, see "Keys" below
            // ... any additional configuration here
        ],
    ],
],
```

If your application just needs some special JWT tools (like validator or parser, a.k.a. Toolset version) use `bizley\jwt\JwtTools` component:

```
[
    'components' => [
        'jwt' => [
            'class' => \bizley\jwt\JwtTools::class,
            // ... any additional configuration here
        ],
    ],
],
```

Of course, if you are already using the Standard version component, you don't need to define the Toolset version component, since the former already provides all the tools.

If you are struggling with the concept of API JWT, here is an [EXAMPLE](INSTRUCTION.md) of how to quickly put all pieces together.

### Available signers

[](#available-signers)

Symmetric:

- HMAC (HS256, HS384, HS512)

Asymmetric:

- RSA (RS256, RS384, RS512)
- ECDSA (ES256, ES384, ES512)
- EdDSA (since 3.1.0)
- BLAKE2B (since 3.4.0)

Signer IDs are available as constants (like Jwt::HS256).

You can also provide your own signer, either as an instance of `Lcobucci\JWT\Signer` or by adding its config to `signers`and `algorithmTypes` and using its ID for `signer`.

> As stated in `lcobucci/jwt` documentation: Although BLAKE2B is fantastic due to its performance, it's not JWT standard and won't necessarily be offered by other libraries.

### Note on signers and minimum bits requirement

[](#note-on-signers-and-minimum-bits-requirement)

Since `lcobucci/jwt 4.2.0` signers require the minimum key length to make sure those are properly secured, otherwise the `InvalidKeyProvided` is thrown.

### Keys

[](#keys)

For symmetric signers `signingKey` is required. For asymmetric ones you also need to set `verifyingKey`. Keys can be provided as simple strings, configuration arrays, or instances of `Lcobucci\JWT\Signer\Key`.

Configuration array can be as the following:

```
[
    'key' => /* key content */,
    'passphrase' => /* key passphrase */,
    'method' => /* method type */,
]
```

- key (`bizley\jwt\Jwt::KEY`) - *string*, default `''`, start it with `@` if it's Yii alias,
- passphrase (`bizley\jwt\Jwt::PASSPHRASE`) - *string*, default `''`,
- method (`bizley\jwt\Jwt::METHOD`) - *string*, default `bizley\jwt\Jwt::METHOD_PLAIN`, available: `bizley\jwt\Jwt::METHOD_PLAIN`, `bizley\jwt\Jwt::METHOD_BASE64`, `bizley\jwt\Jwt::METHOD_FILE`(see )

Simple string keys are shortcuts to the following array configs:

- key starts with `@` or `file://`:

    ```
    [
        'key' => /* given key itself */,
        'passphrase' => '',
        'method' => \bizley\jwt\Jwt::METHOD_FILE,
    ]
    ```

    Detecting `@` at the beginning assumes Yii alias has been provided, so it will be resolved with `Yii::getAlias()`.
- key doesn't start with `@` nor `file://`:

    ```
    [
        'key' => /* given key itself */,
        'passphrase' => '',
        'method' => \bizley\jwt\Jwt::METHOD_PLAIN,
    ]
    ```

### Issuing a token example:

[](#issuing-a-token-example)

Standard version:

```
$now = new \DateTimeImmutable();
/** @var \Lcobucci\JWT\Token\UnencryptedToken $token */
$token = Yii::$app->jwt->getBuilder()
    // Configures the issuer (iss claim)
    ->issuedBy('http://example.com')
    // Configures the audience (aud claim)
    ->permittedFor('http://example.org')
    // Configures the id (jti claim)
    ->identifiedBy('4f1g23a12aa')
    // Configures the time that the token was issued (iat claim)
    ->issuedAt($now)
    // Configures the time that the token can be used (nbf claim)
    ->canOnlyBeUsedAfter($now->modify('+1 minute'))
    // Configures the expiration time of the token (exp claim)
    ->expiresAt($now->modify('+1 hour'))
    // Configures a new claim, called "uid"
    ->withClaim('uid', 1)
    // Configures a new header, called "foo"
    ->withHeader('foo', 'bar')
    // Builds a new token
    ->getToken(
        Yii::$app->jwt->getConfiguration()->signer(),
        Yii::$app->jwt->getConfiguration()->signingKey()
    );
$tokenString = $token->toString();
```

The same in Toolset version:

```
$now = new \DateTimeImmutable();
/** @var \Lcobucci\JWT\Token\UnencryptedToken $token */
$token = Yii::$app->jwt->getBuilder()
    ->issuedBy('http://example.com')
    ->permittedFor('http://example.org')
    ->identifiedBy('4f1g23a12aa')
    ->issuedAt($now)
    ->canOnlyBeUsedAfter($now->modify('+1 minute'))
    ->expiresAt($now->modify('+1 hour'))
    ->withClaim('uid', 1)
    ->withHeader('foo', 'bar')
    ->getToken(
        Yii::$app->jwt->buildSigner(/* signer definition */),
        Yii::$app->jwt->buildKey(/* signing key definition */)
    );
$tokenString = $token->toString();
```

See  for more info.

### Parsing a token

[](#parsing-a-token)

```
/** @var non-empty-string $jwt */
/** @var \Lcobucci\JWT\Token $token */
$token = Yii::$app->jwt->parse($jwt);
```

See  for more info.

### Validating a token

[](#validating-a-token)

You can validate a token or perform an assertion on it (see ).

For validation use:

```
/** @var \Lcobucci\JWT\Token | non-empty-string $token */
/** @var bool $result */
$result = Yii::$app->jwt->validate($token);
```

For assertion use:

```
/** @var \Lcobucci\JWT\Token | string $token */
Yii::$app->jwt->assert($token);
```

You **MUST** provide at least one constraint, otherwise `Lcobucci\JWT\Validation\NoConstraintsGiven` exception will be thrown. There are several ways to provide constraints:

- directly (Standard version only):

    ```
    Yii::$app->jwt->getConfiguration()->setValidationConstraints(/* constaints here */);
    ```
- through component configuration:

    ```
    [
        'validationConstraints' => /*
            array of instances of Lcobucci\JWT\Validation\Constraint

            or
            array of configuration arrays that can be resolved as Constraint instances

            or
            anonymous function that can be resolved as array of Constraint instances with signature
            `function(\bizley\jwt\Jwt|\bizley\jwt\JwtTools $jwt)` where $jwt will be an instance of used component
        */,
    ]
    ```

**Note: By default, this package is not adding any constraints out-of-the-box, you must configure them yourself like in the examples above.**

Using component for REST authentication
---------------------------------------

[](#using-component-for-rest-authentication)

Configure the `authenticator` behavior in the controller.

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

        $behaviors['authenticator'] = [
            'class' => \bizley\jwt\JwtHttpBearerAuth::class,
        ];

        return $behaviors;
    }
}
```

There are special options available:

- jwt - *string* ID of component (default with `'jwt'`), component configuration *array*, or an instance of `bizley\jwt\Jwt`or `bizley\jwt\JwtTools`,
- auth - callable or `null` (default) - anonymous function with signature `function (\Lcobucci\JWT\Token $token)` that should return identity of user authenticated with the JWT payload information. If $auth is not provided method `yii\web\User::loginByAccessToken()` will be called instead.
- throwException - *bool* (default `true`) - whether the filter should throw an exception i.e. if the token has an invalid format. If there are multiple auth filters (CompositeAuth) it can make sense to "silent fail" and pass the validation process to the next filter on the composite auth list.

For other configuration options refer to the [Yii 2 Guide](https://www.yiiframework.com/doc/guide/2.0/en/rest-authentication).

JWT Usage
---------

[](#jwt-usage)

Please refer to the [lcobucci/jwt Documentation](https://lcobucci-jwt.readthedocs.io/en/latest/).

JSON Web Tokens
---------------

[](#json-web-tokens)

-

###  Health Score

57

—

FairBetter than 98% of packages

Maintenance56

Moderate activity, may be stable

Popularity50

Moderate usage in the ecosystem

Community21

Small or concentrated contributor base

Maturity82

Battle-tested with a long release history

 Bus Factor2

2 contributors hold 50%+ of commits

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 ~156 days

Recently: every ~178 days

Total

21

Last Release

584d ago

Major Versions

v1.1.0 → 2.0.02018-11-03

2.0.1 → 3.0.02020-11-28

2.x-dev → 3.0.12021-05-05

3.x-dev → 4.0.02023-02-26

PHP version history (4 changes)v1.0.0PHP &gt;=5.5.0

2.0.0PHP &gt;=7.1.0

3.0.0PHP &gt;=7.4

4.0.0PHP &gt;=8.1

### Community

Maintainers

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

---

Top Contributors

[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (27 commits)")[![bizley](https://avatars.githubusercontent.com/u/8577314?v=4)](https://github.com/bizley "bizley (18 commits)")[![sizeg](https://avatars.githubusercontent.com/u/4047591?v=4)](https://github.com/sizeg "sizeg (12 commits)")[![nadar](https://avatars.githubusercontent.com/u/3417221?v=4)](https://github.com/nadar "nadar (5 commits)")[![githubjeka](https://avatars.githubusercontent.com/u/874234?v=4)](https://github.com/githubjeka "githubjeka (1 commits)")[![AnatolyRugalev](https://avatars.githubusercontent.com/u/1397674?v=4)](https://github.com/AnatolyRugalev "AnatolyRugalev (1 commits)")[![stanfieldr](https://avatars.githubusercontent.com/u/7494573?v=4)](https://github.com/stanfieldr "stanfieldr (1 commits)")

---

Tags

hacktoberfestjwtjwt-authenticationjwt-tokenyii2jwtJWSAuthenticationtokenyii2

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[tymon/jwt-auth

JSON Web Token Authentication for Laravel and Lumen

11.5k49.1M350](/packages/tymon-jwt-auth)[gfreeau/get-jwt-bundle

This Symfony bundle provides a security listener to return a JWT

86591.6k3](/packages/gfreeau-get-jwt-bundle)

PHPackages © 2026

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