yyliziqiu/jwt-auth

JSON Web Token Authentication for yii2

v1.0.2 2019-10-16 03:26 UTC

This package is not auto-updated.

Last update: 2020-08-06 08:11:28 UTC


README

>在yii2框架下使用的JWT。

配置文件

    'components' => [
        'tokenManager' => [
            'class' => 'JwtAuth\Manager',
            'identityClass' => 'app\models\Visitor',
            'enableWhitelist' => true,
            'enableCookie' => true,
            'salt' => 'L3AeVgpV70I9HouNFd06bYjmdG7bFE4F',
            'ttl' => 86400,
            'refreshTtl' => 86400*30,
            'cache' => [
                'class' => 'yii\redis\Cache',
                'redis' => [
                    'hostname' => 'localhost',
                    'port' => 6379,
                    'database' => 0,
                ]
            ]
        ]
    ]
  • 如果没有配置cache,默认使用 Yii::$app->cache。或cache配置为'cache'=>'redisCache'则使用Yii::$app->redisCache
  • identityClass指定的类需要实现JwtAuth\IdentityInterface接口。
  • ttl为过期时间。在此时间内,token 是有效的。这个过期时间必须大于签发时间。单位:秒。
  • refreshTtl为刷新时间。在此时间内,token是可以被刷新的,即使token已经失效。若想禁用token刷新机制,可设置refreshTtl大于ttl。单位:秒。
  • salt为token的加密秘钥。

生成token

try {
    $this->manager()->createToken();
} catch (UnauthorizedException $ex) {
    
}

验证token

try {
    $user = $this->manager()->verifyToken();
} catch (TokenInvalidException $ex) {
    
} catch (UnauthorizedException $ex) {
    
}

$user->getContent();
$user->getClaims();

注销token

Yii::$app->get('tokenManager')->invalidateToken();

获取token认证后的用户实例

$user = Yii::$app->get('tokenManager')->identity();

示例

<?php

namespace app\models;

use JwtAuth\Models\AbstractIdentityModel;

class Visitor extends AbstractIdentityModel
{
    /**
     * @var string 游客 id
     */
    public $clientId;

    /**
     * @var int 设备类型
     */
    public $clientType;

    /**
     * {@inheritdoc}
     */
    public static function getIdentityById($id, $claims, $content)
    {
        $visitor = new Visitor();
        $visitor->clientId = $id;
        $visitor->clientType = $claims['cty'];

        return $visitor;
    }

    /**
     * {@inheritdoc}
     */
    public static function getIdentityByRequest($request)
    {
        $visitor = new Visitor();
        $visitor->clientId = 0101;
        $visitor->clientType = 'android';

        return $visitor;
    }

    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return $this->clientId;
    }

    /**
     * {@inheritdoc}
     */
    public function genClaims()
    {
        return ['aud' => 'visitor', 'cty' => $this->clientType];
    }

    /**
     * {@inheritdoc}
     */
    public function genContent()
    {
        return ['age' => 20];
    }

    /**
     * {@inheritdoc}
     */
    public function quit()
    {
        return true;
    }
}