PHP的jwttoken生成和验证

TOKENUTILS类:

<?php

namespace app\common\utils;
class TokenUtils
{
    private $signKey = SIGNKEY;

    private $header = [
        'typ' => 'JWT',
        'alg' => 'SHA256',
    ];

    private $payload = [];

    function __construct()
    {
        $expiresAt = strtotime('+10hour');
        $this->withExpiresAt($expiresAt);
    }

    public function withPayload($payload)
    {
        $this->payload = $payload;
        return $this;
    }

    public function withClaim($key, $value)
    {
        $this->payload[$key] = $value;
        return $this;
    }

    public function withExpiresAt($expiresAt)
    {
        $this->withClaim('exp', $expiresAt);
        return $this;
    }

    public function withIdentity($identity)
    {
        $this->withClaim('jti', $identity);
        return $this;
    }

    public function getClaim($key)
    {
        return $this->payload[$key] ?? null;
    }

    private function signature($data, $signKey, $alg)
    {
        return hash_hmac($alg, $data, $signKey, true);
    }

    public function createToken()
    {
        $base64header = base64_encode(json_encode($this->header));
        $base64payload = base64_encode(json_encode($this->payload));
        $data = $base64header . '.' . $base64payload;
        $signature = $this->signature($data, $this->signKey, $this->header['alg']);
        $base64signature = base64_encode($signature);
        $token = $data . '.' . $base64signature;
        return $token;
    }

    public function getDecodePayload($token)
    {
        $result = null;
        try {
            list($base64header, $base64payload, $signature) = explode('.', $token);
            $data = $base64header . '.' . $base64payload;

            $newSignature = $this->signature($data, $this->signKey, $this->header['alg']);
            $newSignature = base64_encode($newSignature);

            if ($newSignature == stripslashes($signature)) {
                $payload = base64_decode($base64payload);
                $result = json_decode($payload, true);
            }
        } catch (\Exception $e) {

        }
        return $result;
    }

    public function verifyToken($token)
    {
        $result = false;
        $arr = $this->getDecodePayload($token);
        if (isset($arr['exp']) && $arr['exp'] > time()) {
            $result = true;
        }
        return $result;
    }
}

生成token:

$tokenUtils=new TokenUtils();
$tokenUtils->withClaim("uname",USERNAME);
$tokenUtils->withClaim("uid",UID);
$token=$tokenUtils->createToken();

验证token:

$tokenUtils=new TokenUtils();
$flag=$tokenUtils->verifyToken($token);//返回true验证通过,返回false,验证失败,可能是验签失败,也可能是已经过期。

评论

(= ̄ω ̄=)··· 暂无内容!

回复

您还未登录,请先登录或者注册