欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

PHP实现JWT鉴权Token

程序员文章站 2022-05-19 08:25:47
...
<?php
/**
 * PHP实现jwt
 */
class Jwt {

    //头部
    private static $header=array(
        'alg'=>'HS256', //生成signature的算法
        'typ'=>'JWT'    //类型
    );

    //使用HMAC生成信息摘要时所使用的**
    private static $key = "";

    public function __construct()
    {
        //实际开发中,如果不是做动态登录token,而是做某个接口token验证,可以把$key设置成分配好权限的随机值
        self::$key = time();
    }

    public static function getToken(array $payload)
    {
        if(is_array($payload))
        {
            $header=urlencode(json_encode(self::$header,true));
            $payload=urlencode(json_encode($payload,true));
            $token=$header.'.'.$payload.'.'.urlencode($header . $payload . self::$key . self::$header['alg']);
            return $token;

            //实际开发时,将token和expireTime放到user表,setTime放到日志表
            /*
                 $user_id = 1;
                $setTime = time();
                $expireTime = time() + 7200;
                $sql1 = "update user  where user_id = $user_id set setTime = $expireTime";
                $sql2 = "insert into log (user_id, set_time) values ($user_id, $setTime)";
            */
        }else{
            return false;
        }
    }


    public static function verifyToken($Token)
    {
        $tokens = explode('.', $Token);
        if (count($tokens) != 3)
            return false;

        list($header, $payload, $sign) = $tokens;

        //获取jwt算法
        if (empty(json_decode(urldecode($header), true)['alg'])){
            return '签名算法不匹配';
        }

        //签名验证
        if (urlencode($header . $payload . self::$key  . self::$header['alg']) !== $sign)
            return '签名错误';

        $payload = json_decode(urldecode($payload), JSON_OBJECT_AS_ARRAY);

        /*实际开发时,验证当前时间是否比user表中的expireTime大*/
        if (isset($payload['expireTime']) && $payload['expireTime'] < time())
            return '签名失效';

        return $payload;
    }


}

echo "<pre>";
$payload = array('username'=>'i am username','password'=>'i am password');//规则可以自定义,本人喜欢用账号和密码
var_dump($payload);
$jwt = new Jwt;
$token = $jwt->getToken($payload);
echo $token;

//对token进行验证签名
$getPayload = $jwt->verifyToken($token);
echo "<br><br>";
var_dump($getPayload);
echo "<br><br>";
//接下来
//开发中先判断$getPayload中是否存在自定义规则的指定字段,不存在失败
//然后去验证当前用户的username,password,token是否在user表中存在记录,不存在失败

 

相关标签: JWT Token 鉴权