klsoft/yii2-jwt-auth

The package provides a Yii 2 authentication method based on a JWT token.

Installs: 0

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/klsoft/yii2-jwt-auth

1.0.0 2025-12-31 12:35 UTC

This package is auto-updated.

Last update: 2025-12-31 12:58:22 UTC


README

The package provides a Yii 2 authentication method based on a JWT token.

Requirement

  • PHP 8.0 or higher.

Installation

composer require klsoft/yii2-jwt-auth

How to use

1. Implement Klsoft\Yii2JwtAuth\JwksProviderInterface

Example:

namespace MyNamespace;

use Klsoft\Yii2JwtAuth\JwksProviderInterface;

class JwksProvider implements JwksProviderInterface
{
    private const JWKS = 'jwks';

    public function __construct(private string $jwksUrl)
    {
    }

    function getKeys(): array
    {
        $keys = Yii::$app->cache->get(JwksProvider::JWKS);
        if ($keys === false) {
            $options = [
                'http' => [
                    'ignore_errors' => true,
                    'method' => 'GET'
                ],
            ];
            $responseData = file_get_contents($this->jwksUrl, false, stream_context_create($options));
            if (!empty($responseData)) {
                $keys = json_decode($responseData, true);
                Yii::$app->cache->set(
                    JwksProvider::JWKS, 
                    $keys, Yii::$app->params['jwksKeysCacheDuration']);
                    return $keys;
            }
        } else {
            return $keys;
        }

        return [];
    }
}

2. Add the JWKS URL to param.php

Example:

return [
    'jwksUrl' => 'http://localhost:8080/realms/myrealm/protocol/openid-connect/certs',
    'jwksCacheDuration' => 60 * 3
];

3. Register dependencies

Example of registering dependencies using the application configuration:

'container' => [
        'definitions' => [
            'Klsoft\Yii2JwtAuth\HttpJwtAuth' => [
                'Klsoft\Yii2JwtAuth\HttpJwtAuth',
                [Instance::of('Klsoft\Yii2JwtAuth\JwksProviderInterface')]
            ],
        ],
        'singletons' => [
            'Klsoft\Yii2JwtAuth\JwksProviderInterface' => [
                'MyNamespace\JwksProvider',
                [$params['jwksUrl']]
            ]
        ]
    ]

4. Configure the authenticator behavior

Example:

class MyController extends Controller
{
    public function __construct(private HttpJwtAuth $httpJwtAuth)
    {
    }

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = $this->httpJwtAuth;
        return $behaviors;
    }
}