davidxu/yii2-jwt

A JWT extension based on Icobucci

Installs: 4

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 1

Forks: 0

Open Issues: 0

Type:yii2-extension

1.0.0 2023-02-28 05:42 UTC

This package is auto-updated.

Last update: 2024-10-28 09:17:13 UTC


README

This extension provides the JWT integration for the Yii framework 2.0.

Table of contents

  1. Installation
  2. Dependencies
  3. Basic usage
    1. Generating public and private keys
    2. Use as a Yii component
    3. Use as a Yii params
    4. Creating
    5. Parsing from strings
    6. Validating
  4. Yii2 advanced template example

Installation

Package is available on Packagist, you can install it using Composer.

composer require davidxu/yii2-jwt

Dependencies

  • PHP 8.0+
  • OpenSSL Extension

Basic usage

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

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

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

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

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

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

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

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)));
}