首页 / 后端开发 / JWT-实现token用户身份验证机制

JWT-实现token用户身份验证机制

2023-02-28 02:28 后端开发 阅读 10376 来源 php先锋网

1. 引入php-jwt包

composer require firebase/php-jwt

2. 生成token

//生成token
public function createJwt($userId = 'zq')
{
    $key = md5('heghdrwgsd'); //jwt的签发密钥,验证token的时候需要用到
    $time = time(); //签发时间
    $expire = $time + 100; //过期时间
    $token = array(
        "user_id" => $userId,
        "iss" => "https://www.phpvan.com/",//签发组织
        "aud" => "zhangqi", //签发作者
        "iat" => $time,
        "nbf" => $time,
        "exp" => $expire
    );
    $jwt = JWT::encode($token, $key, 'HS256');
    return $jwt;
}

3. 验证token

//校验jwt权限API
public function verifyJwt($jwt = '')
{
    $key = md5('heghdrwgsd');
    try {
        $jwtAuth = json_encode(JWT::decode($jwt, new Key($key, 'HS256')));
        $authInfo = json_decode($jwtAuth, true);
        $msg = [];
        if (!empty($authInfo['user_id'])) {
            $msg = [
                'status' => 1001,
                'msg' => 'Token验证通过'
            ];
        } else {
            $msg = [
                'status' => 1002,
                'msg' => 'Token验证不通过,用户不存在'
            ];
        }
        return $msg;
    }  catch (\Firebase\JWT\ExpiredException $e) {
        echo json_encode([
            'status' => 1003,
            'msg' => 'Token过期'
        ]);
        exit;
    } catch (\Exception $e) {
        echo json_encode([
            'status' => 1002,
            'msg' => 'Token无效'
        ]);
        exit;
    }
}

以上为加解密方式,也可以用于参数加密, 在数组后面追加上个字段,例如 data

$token = array( "user_id" => $userId, "iss" => "https://www.phpvan.com/",//签发组织 "aud" => "zhangqi", //签发作者 "iat" => $time, "nbf" => $time, "exp" => $expire, "data" = []);

如对你有帮助,请多多分享,站点是php先锋网

猜你喜欢