You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Bearer授权JWT时遇“kid为空无法查找密钥”错误求助

解决JWT授权报错:"kid" empty, unable to lookup correct key

错误原因

这个错误大多出现在Firebase JWT库v6.x及以上版本中——从该版本开始,JWT::decode方法不再直接接受密钥字符串作为第二个参数,要求必须传入Firebase\JWT\Key实例。你的代码仍沿用旧版本的解码逻辑,导致库无法正确识别密钥,进而抛出"kid为空"的错误(即便你的Token本身没有包含kid字段)。

解决方案

1. 引入Key类

在JwtHandler.php中添加Key类的引入语句:

use Firebase\JWT\JWT;
use Firebase\JWT\Key; // 新增该行

2. 修改解码方法逻辑

将jwtDecodeData方法中的解码代码替换为使用Key实例的写法:

public function jwtDecodeData($jwt_token){
    try{
        // 替换原解码逻辑,传入Key实例
        $decode = JWT::decode($jwt_token, new Key($this->jwt_secret, 'HS256'));
        return[
            "data" => $decode->data
        ];
    }catch(Exception $e){
        return[
            "message" => $e->getMessage()
        ];
    }
}

3. 额外检查项

  • 确认Postman中Authorization头格式正确:Bearer <你的Token>,确保Token没有多余空格或特殊字符;
  • 验证生成Token与解码时的密钥完全一致(你的代码中已保持一致,此部分无需修改);
  • 若使用旧版本JWT库,可更新至最新稳定版:
    composer update firebase/php-jwt
    

修改后的完整JwtHandler代码

<?php
require './vendor/autoload.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key; // 新增Key类引入

class JwtHandler{

    protected $jwt_secret;
    protected $token;
    protected $issuedAt;
    protected $expired;
    protected $jwt; // 修复原代码语法错误:补全变量前的空格

    public function __construct(){
        //default time zone
        date_default_timezone_set('Europe/London');
        $this->issuedAt=time();

        //token valid for
        $this->expired=$this->issuedAt + 3600;

        //set secret key
        $this->jwt_secret='8mw37mn_1)$xjg=)$%5-eavqjo6+=yj3gma0-xwl0%5e7he9e';

    }

    public function jwtEncodeData($iss,$data){
        $this->token =array(
            //Adding identifier who issued token
            "iss"=>$iss,
            "aud"=>$iss,
            //Addingcurrent timestamp to token, when it was issue
            "iat"=>$this->issuedAt,
            //Token expiration
            "exp"=>$this->expired,
            //Payload
            "data"=>$data

        );
        $this->jwt=JWT::encode($this->token, $this->jwt_secret, 'HS256');
        return $this->jwt;

    }


    public function jwtDecodeData($jwt_token){
        try{
            $decode = JWT::decode($jwt_token, new Key($this->jwt_secret, 'HS256'));
            return[
                "data" => $decode->data
                ];
        }catch(Exception $e){
            return[
                "message" => $e->getMessage()
                ];
        }

    }

}

?>

内容的提问来源于stack exchange,提问作者jordan o'donoghue

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 05:36:00