PHP code example of davidxu / yii2-jwt

1. Go to this page and download the library: Download davidxu/yii2-jwt library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

davidxu / yii2-jwt example snippets


'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'
    ],
],

return [
    //...
    'jwt' => [
        'privateKey' => __DIR__ . '/../private.key',
        'publicKey' => __DIR__ . '/../public.key',
        'expire_time' => '+2 hour'
    ],
    //...
];

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

$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();

$jwt = new davidxu\jwt\Jwt();
// OR 
// $jwt = Yii::$app->jwt;
$token = $jwt->parseToken($token);
echo $token->claims()->get('uid'); // will print "12345"

$jwt = new davidxu\jwt\Jwt();
// OR 
// $jwt = Yii::$app->jwt;
$valid = $jwt->validateToken($token, true, [
    'app_id' => Yii::$app->id,
    ], 'uid'); // return 12345(uid)

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