thinkphp6 token令牌 生成详解

2023-05-11 15:59:29 浏览数 (3)

composer 安装 composer require lcobucci/jwt 3.3 在extend/tools/jwt创建Token.php 注意:如果没有该目录,则自行创。

生成Token(createToken)

代码语言:javascript复制
<?php
namespace toolsjwt;

use LcobucciJWTBuilder;
use LcobucciJWTParser;
use LcobucciJWTSignerHmacSha256;
use LcobucciJWTValidationData;

/**
 * Created by PhpStorm.
 * User: asus
 * Date: 2019/4/5
 * Time: 13:02
 */
class Token
{
     public static function createToken($uid = null)
     {
            $signer = new Sha256();//加密规则
            $time = time();//当前时间

            $token = (new Builder())
                ->issuedBy('teacher')//签发人
                ->canOnlyBeUsedBy('student')//接收人
                ->identifiedBy('MarsLei', true) //标题id
                ->issuedAt($time)//发出令牌的时间
                ->canOnlyBeUsedAfter($time) //生效时间(即时生效)
                ->expiresAt($time   3600) //过期时间
                ->with('uid', $uid) //用户id
                ->sign($signer, 'my') //签名
                ->getToken(); //得到token
            return (string)$token;
        }
}

验证Token(verifyToken)

代码语言:javascript复制
public static function verifyToken($token=null){
        //检测是否接收到了token
        if(empty($token)){
            return 0;
        }
        //转化为可以验证的token
        $token = (new Parser())->parse((string) $token);
        //验证基本设置
        $data = new ValidationData();
        $data->setIssuer('teacher');
        $data->setAudience('student');
        $data->setId('MarsLei');

        if(!$token->validate($data)){
            return 0;
        }
        //验证签名
        $signer = new Sha256();
        if(!$token->verify($signer, 'my')){
            return 0;
        }
        //验证通过,返回用户id
        return $token->getClaim('uid');
    }

获取Token(getRequestToken)

代码语言:javascript复制
public static function getRequestToken()
    {
        if (empty($_SERVER['HTTP_AUTHORIZATION'])) {
            return false;
        }

        $header = $_SERVER['HTTP_AUTHORIZATION'];
        $method = 'bearer';
        //去除token中可能存在的bearer标识
        return trim(str_ireplace($method, '', $header));
    }

回收实例

重写apache

代码语言:javascript复制
    RewriteCond %{HTTP:Authorization} ^(. )$
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

回收token

代码语言:javascript复制
    //清空token  将需清空的token存入缓存,再次使用时,会读取缓存进行判断
    $token = Token::getRequestToken();
    $delete_token = cache('delete_token') ?: [];
    $delete_token[] = $token;
    cache('delete_token', $delete_token, 86400);
    $this->ok();

1 人点赞