shyn/jwt-auth

json web token

v1.1.0 2019-01-18 08:58 UTC

This package is not auto-updated.

Last update: 2024-05-30 23:25:27 UTC


README

>在yii2框架下使用的jwt-auth。

配置文件

    'components' => [
        'jwtManager' => [
            'class' => 'JwtAuth\Manager',
            'userClass' => 'app\models\User',
            'whitelistEnable' => true,
            'blacklistEnable' => false,
            'salt' => 'L3AeVgpV70I9HouNFd06bYjmdG7bFE4F',
            'ttl' => 20,
            'refreshTtl' => 40,
            'cache' => [
                'class' => 'yii\redis\Cache',
                'redis' => [
                    'hostname' => 'localhost',
                    'port' => 6379,
                    'database' => 0,
                ]
            ]
        ]
    ]
  1. 如果没有配置cache,默认使用 Yii::$app->cache。或cache配置为'cache'=>'redisCache'则使用Yii::$app->redisCache
  2. userClass指定的类需要实现JwtAuth\UserAuthInterface接口。
  3. ttl为token有效时长,refreshTtl为token刷新有效时长,若想禁用token刷新机制,可设置refreshTtl大于ttl。单位:秒。
  4. salt为token的加密秘钥。

生成token

    public function actionLogin()
    {
        $token = Yii::$app->jwtManager->createToken();

        return $token;
    }

验证token

    public function behaviors()
    {
        return [
            'jwtFilter' => [
                'class' => \JwtAuth\Filters\AuthFilter::class,
                'except' => ['login']
            ],
        ];
    }

注销token

    public function actionLogout()
    {
        Yii::$app->jwtManager->invalidateToken();
        
        return 'successfully!';
    }

获取token认证后的用户实例

    public function actionUser()
    {
        $user = $identify=Yii::$app->jwtManager->user();
        
        return $user->name;
    }

User示例

<?php

namespace app\models;

use JwtAuth\Models\AbstractIdentityModel;

class User extends AbstractIdentityModel
{
    public $id;
    public $name;
    public $password;
    public $email;

    public static function getUserById($id)
    {
        $user = new User();
        $user->id = 1;
        $user->name = 'yyliziqiu';
        $user->password = '123456';
        $user->email = 'yyliziqiu@163.com';

        return $user;
    }

    public static function getUserByRequest($request)
    {
        $user = new User();
        $user->id = 1;
        $user->name = 'yyliziqiu';
        $user->password = '123456';
        $user->email = 'yyliziqiu@163.com';

        return $user;
    }

    public function getId()
    {
        return $this->id;
    }

    public function genCustomClaims()
    {
        return ['name' => 'yyliziqiu', 'aud' => 'phone'];
    }

    public function genContent()
    {
        return ['address' => 'Hebei'];
    }
}