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

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

algsupport/jwt
==============

JWT integration for Yii 2

v0.0.3(2y ago)05Apache-2.0PHPPHP &gt;=8.2

Since Jan 9Pushed 2y agoCompare

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

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

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

See [lcobucci/jwt](https://github.com/lcobucci/jwt) repo for details about the version.

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

[](#installation)

Add the package to your `composer.json`:

```
{
    "require": {
        "algsupport/jwt": "*"
    }
}
```

and run `composer update` or alternatively run `composer require algsupport/jwt`

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 `algsupport\jwt\Jwt` component:

```
[
    'components' => [
        'jwt' => [
            'class' => \algsupport\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 `algsupport\jwt\JwtTools` component:

```
[
    'components' => [
        'jwt' => [
            'class' => \algsupport\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 (`algsupport\jwt\Jwt::KEY`) - *string*, default `''`,
- passphrase (`algsupport\jwt\Jwt::PASSPHRASE`) - *string*, default `''`,
- method (`algsupport\jwt\Jwt::METHOD`) - *string*, default `algsupport\jwt\Jwt::METHOD_PLAIN`, available: `algsupport\jwt\Jwt::METHOD_PLAIN`, `algsupport\jwt\Jwt::METHOD_BASE64`, `algsupport\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' => \algsupport\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' => \algsupport\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(\algsupport\jwt\Jwt|\algsupport\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' => \algsupport\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 `algsupport\jwt\Jwt`or `algsupport\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

22

—

LowBetter than 22% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity4

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 51% 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 ~0 days

Total

3

Last Release

858d ago

PHP version history (2 changes)v0.0.1PHP &gt;=8.1

v0.0.2PHP &gt;=8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/7ace2d281a54f804ff421c5061bc5a588502d2f3c3f4cd62f5d989b4dc1e1ad3?d=identicon)[algsupport](/maintainers/algsupport)

---

Top Contributors

[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (26 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)")[![bizley](https://avatars.githubusercontent.com/u/8577314?v=4)](https://github.com/bizley "bizley (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

jwtJWSAuthenticationtokenyii2

### Embed Badge

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

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

###  Alternatives

[tymon/jwt-auth

JSON Web Token Authentication for Laravel and Lumen

11.5k49.1M350](/packages/tymon-jwt-auth)[namshi/jose

JSON Object Signing and Encryption library for PHP.

1.8k99.6M101](/packages/namshi-jose)[bizley/jwt

JWT integration for Yii 2

67425.3k2](/packages/bizley-jwt)[gfreeau/get-jwt-bundle

This Symfony bundle provides a security listener to return a JWT

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

Authenticated and encrypted API tokens using modern crypto.

52309.2k1](/packages/tuupola-branca)[internacionalweb/cognito-token-verifier

This library verifies that the signature of the JWT is valid, comes from a desired application, and that the token has not been tampered with or expired.

102.1k](/packages/internacionalweb-cognito-token-verifier)

PHPackages © 2026

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