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

PHP中JWT::decode()提示Header传值为null及CORS跨域问题求助

问题解决方案

一、修复CORS跨域问题

核心问题

  1. 响应头拼写错误:原代码中Access-Conrol-Allow-Credentials少写了字母l,正确字段名是Access-Control-Allow-Credentials。
  2. 未处理OPTIONS预请求:跨域请求前浏览器会发送OPTIONS预请求验证权限,当前代码未返回200状态,导致预请求失败,后续正常请求被拦截。

修改后的CORS处理代码

在PHP代码最顶部添加OPTIONS请求处理,并修正响应头:

// 处理OPTIONS预请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

require_once 'vendor/autoload.php';
require_once 'connection.php';
header("Content-Type: application/json");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Access-Control-Allow-Methods: POST, GET, PUT, OPTIONS, DELETE");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: *");

二、修复JWT获取与解码报错

核心问题

  1. CORS未修复时,Authorization头无法正常传递到后端,导致$headers["Authorization"]不存在。
  2. 直接访问数组键和调用explode,未做任何校验,null值传入引发后续报错。
  3. 客户端可能存在token不存在的情况,导致Authorization头格式无效。

修改后的PHP代码(JWT部分)

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

$skey = 'some_crazy_long_secret_key_I_used';
$headers = getallheaders();

// 检查Authorization头是否存在
if (!isset($headers["Authorization"])) {
    http_response_code(401);
    echo json_encode(['error' => 'Authorization header missing']);
    exit;
}

$jwt = $headers["Authorization"];
// 校验Bearer token格式
$tokenParts = explode(" ", $jwt);
if (count($tokenParts) !== 2 || strtolower($tokenParts[0]) !== 'bearer') {
    http_response_code(401);
    echo json_encode(['error' => 'Invalid Authorization header format']);
    exit;
}

$mainJwt = $tokenParts[1];
// 解码JWT并捕获异常
try {
    $decoded_jwt = JWT::decode($mainJwt, new Key($skey, 'HS256'));
    echo json_encode(['message' => 'done!', 'data' => (array)$decoded_jwt]);
} catch (Exception $e) {
    http_response_code(401);
    echo json_encode(['error' => 'Invalid or expired token', 'details' => $e->getMessage()]);
}

客户端代码优化(避免无效请求)

增加token存在性判断,确保只有存在有效token时才发送请求:

const token = localStorage.getItem('token');
if (!token) {
    console.error('No token found in localStorage');
    return;
}

axios.get(`${API_URL}`, {
    headers: {
        Authorization: `Bearer ${token}`
    }
}).then((response)=>{console.log(response.data)})
.catch((error)=>{console.error('Request failed:', error.response?.data || error.message)});

内容的提问来源于stack exchange,提问作者Praise codes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 18:25:29