php-jwt 封装 JWT 加解密

最后更新于:2022-04-02 02:23:35

[TOC] > [github](https://github.com/firebase/php-jwt) > [JWT JSON Web Token 验证](../../../%E5%85%B6%E4%BB%96/JWTJSONWebToken%E9%AA%8C%E8%AF%81.md) ## 安装 ``` composer require firebase/php-jwt ``` ## 使用 ``` use \Firebase\JWT\JWT; $key = "example_key"; $token = array( "iss" => "http://example.org", /* 签发人 */ "aud" => "http://example.com", /* 受众 */ "iat" => 1356999524, /* 签发时间 */ "nbf" => 1357000000 /* 生效时间 */ ); // encode $jwt = JWT::encode($token, $key,'HS256'); //默认就是 'HS256' echo $jwt.PHP_EOL; //eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9leGFtcGxlLm9yZyIsImF1ZCI6Imh0dHA6XC9cL2V4YW1wbGUuY29tIiwiaWF0IjoxMzU2OTk5NTI0LCJuYmYiOjEzNTcwMDAwMDB9.KcNaeDRMPwkRHDHsuIh1L2B01VApiu3aTOkWplFjoYI //decode $decoded = JWT::decode($jwt, $key, array('HS256')); $decoded_array = (array) $decoded; print_r($decoded_array); /** * Array ( [iss] => http://example.org [aud] => http://example.com [iat] => 1356999524 [nbf] => 1357000000 ) */ /** * 当签名服务器和验证服务器之间存在时钟偏差时,您可以添加一个可以解释的余地。建议这种回旋余地不应超过几分钟 */ JWT::$leeway = 60; // $leeway in seconds $decoded = JWT::decode($jwt, $key, array('HS256')); ```
';