jwt 校验抛出异常改为返回false
最新推荐文章于 2025-11-26 13:46:58 发布
本文介绍了一种基于私钥设置Token并使用公钥进行Token信息验证的方法。该方法通过设置Token的有效期,并利用私钥签名确保了Token的安全性。同时,文章提供了验证Token有效性的逻辑,包括检查Token是否已过期。
本文介绍了一种基于私钥设置Token并使用公钥进行Token信息验证的方法。该方法通过设置Token的有效期,并利用私钥签名确保了Token的安全性。同时,文章提供了验证Token有效性的逻辑,包括检查Token是否已过期。
public static function setToken($account_id, $privateKey) { $signer = new Sha256(); $keychain = new Keychain(); $token = (new Builder()) ->setExpiration(time() + 3600) ->set('account_id', $account_id) ->sign($signer, $keychain->getPrivateKey(RSA::formatPrivateKey("{$privateKey}"))) ->getToken(); return (string) $token; } public static function getTokenInfo($token, $publicKey) { $signer = new Sha256(); $keychain = new Keychain();
这样可以实现如果抛出异常时返回false
try { $token = (new Parser())->parse((string) $token); } catch (\Exception $e) { return false; } if(!@$token->verify($signer, @$keychain->getPublicKey(RSA::formatPublicKey("{$publicKey}")))) return false; if(@$token->getClaim('exp') > time()){ return @$token->getClaim('account_id'); } return false; } }
440

被折叠的 条评论
为什么被折叠?