thinkphp如何使用jwt

这篇博客介绍了如何使用JWT(JSON Web Tokens)进行身份验证和信息加密。首先通过composer安装JWT库,然后创建包含用户信息和过期时间的payload。接着使用JWT::encode方法生成加密的token。最后,通过JWT::decode方法解码token,获取原始信息。整个过程涉及到的主要概念包括 iss、exp、sub等JWT标准字段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先安装JWT

composer require firebase/php-jwt

生成token

数据准备
准备一个需要的用户信息
     $account = ['id' => 'root', 'password' => 123456];
准备一个$payload
     $payload=[
            "userinfo"=>$account,
            "exp"=>time()+3600*24  //过期时间
  					
        ];


不限于以下
iss:发行人
exp:到期时间
sub:主题
aud:用户
nbf:在此之前不可用
iat:发布时间
jti:JWT ID用于标识该JWT

  
  使用JWT::encode	方法加密
    第一个参数是 我们准备的数据
    第二个参数是 我们自己知道但是不能泄露的加密的盐
    第三个参数是 加密方式  要与解密保持一致
  
  $token = JWT::encode($payload, $saline, 'HS256');
  
会返回一个token
 eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyaW5mbyI6eyJpZCI6InJvb3QiLCJwYXNzd29yZCI6MTIzNDU2fSwiZXhwIjoxNjQ0NDczMDc3fQ.04M_baRDceG-kL5hjuA6CPpJDuac71OewOjidjEwW8Y
  
 
  以AA.BB.YY格式其中BB段为使用base64编码的$payload,是可逆的
 
  

使用token返回信息(解码)

使用JWT::decode进行解码
第一个参数是我们刚才生成的token
第二个参数是一个Key对象 可由use Firebase\JWT\Key; 实例化一个key
过程中传入与encode 过程中相同的盐和加密方式作为参数

$decode = JWT::decode($token, new Key($saline, 'HS256'));
$decode返回
stdClass Object ( [userinfo] => stdClass Object ( [id] => root [password] => 123456 ) [exp] => 1644473077 )




### ThinkPHP 8 中 JWT 使用教程 #### 安装依赖库 为了在 ThinkPHP 8 中使用 JWT,需先安装 `firebase/php-jwt` 库。可以通过 Composer 来完成此操作: ```bash composer require firebase/php-jwt ``` #### 创建 JWT 工具类 创建一个新的工具类用于处理 JWT 的生成与解析工作。 ```php <?php namespace app\common\tool; use Firebase\JWT\JWT; use Firebase\JWT\Key; class JwtTool { private static $key = "example_key"; /** * Generate a new token. * * @param array $payload Payload data to be included in the token. * @return string Generated JWT token. */ public static function generateToken(array $payload): string { return JWT::encode($payload, self::$key, 'HS256'); } /** * Decode an existing token and verify its validity. * * @param string $token The JWT token that needs decoding. * @throws Exception If there is any issue during decode process or validation fails. * @return object Decoded payload as stdClass object. */ public static function parseToken(string $token) :object { try { $decoded = JWT::decode($token, new Key(self::$key, 'HS256')); return (array)$decoded; } catch (\Exception $e) { throw new \Exception('Invalid Token', 401); } } } ``` #### 用户登录逻辑实现 当用户成功登录后,可以利用上述定义的方法来创建一个带有有效载荷(Payload)的令牌,并将其作为响应的一部分发送给客户端[^2]。 ```php public function login() { // Assume username/password verification has been done here... // Prepare payload with necessary information about this session/user $payload = [ 'iss' => request()->domain(), 'iat' => time(), 'exp' => time() + 3600, 'nbf' => time(), 'sub' => $userId, 'email'=> $userEmail ]; // Create JSON Web Token using our custom tool method $jwt = JwtTool::generateToken($payload); // Respond back to client including generated jwt within headers header("Authorization: Bearer {$jwt}"); echo json(['status'=>'success','message'=>"Login successful"]); } ``` #### 请求认证中间件设置 为了让每次 HTTP 请求都能自动校验传入的身份验证头信息中的 JWT 是否合法,在应用入口处配置全局过滤器或编写专门针对 API 路由组使用的中间件来进行这项检查。 ```php // application/middleware/JWTAuth.php namespace app\middleware; use Closure; use think\Exception; use app\common\tool\JwtTool; class JWTAuth { protected $ignoreUrls = []; public function handle($request, Closure $next){ // Ignore specific urls from being authenticated via JWT foreach ($this->ignoreUrls as $urlPattern) { if(preg_match("#^{$urlPattern}$#", strtolower($request->path()))){ return $next($request); } } // Extract Authorization Header Value list($header,) = explode(' ', $request->header('authorization'), 2)+['']; switch(strtolower(trim($header))){ case '': throw new Exception('Missing authorization header.', 401); case 'bearer': break; default : throw new Exception('Unsupported authentication scheme.', 401); } // Validate provided token against secret key stored server side only try { $data = JwtTool::parseToken($request->server('HTTP_AUTHORIZATION')); // Attach decoded claims onto current Request instance for later use inside controllers $request->withData([ ...$request->getData(), '_auth_claims_' => $data ]); return $next($request); }catch(\Exception $ex){ throw new Exception($ex->getMessage(), $ex->getCode()); } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值