阅读背景:

简易版JWT 生成token_lanjinghexuan的博客

来源:互联网 
<?php

namespace tool\token;

use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\ValidationData;


class Token
{
    public static function toke($id){
        $signer = new Sha256();
        $time = time();
        $token = (new Builder())->issuedBy('https://tp.com') // Configures the issuer (iss claim)
        ->canOnlyBeUsedBy('https://729.org') // Configures the audience (aud claim)
        ->identifiedBy(1, true) // Configures the id (jti claim), replicating as a header item
        ->issuedAt($time) // Configures the time that the token was issue (iat claim)
        ->canOnlyBeUsedAfter($time -1) // Configures the time that the token can be used (nbf claim)
        ->expiresAt($time + 86400) // Configures the expiration time of the token (exp claim)
        ->with('uid', $id)->sign($signer,'zhangsan') // Configures a new claim, called "uid"
        ->getToken();
        return (string)$token;
    }
    
    public static function getToke($token){
        $user_id=null;
        $token = (new Parser())->parse((string) $token);
        $data = new ValidationData(); // It will use the current time to validate (iat, nbf and exp)
        $data->setIssuer('https://tp.com');
        $data->setAudience('https://729.org');
        $data->setId(1);
        if (!$token->validate($data)) {
            return 11;
        }
        $signer = new Sha256();
        if (!$token->verify($signer, 'zhangsan')) {
            //签名验证失败
            return 22;
        }
        //从token中获取用户id
        $user_id = $token->getClaim('uid');
        return $user_id;
    }

}
<?php

namespace tool\token;

use Lcobucci\JWT\



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: