通过标头进行 JWT 授权引发 CORS 错误

Posted

技术标签:

【中文标题】通过标头进行 JWT 授权引发 CORS 错误【英文标题】:JWT Authorization via header throws CORS Error 【发布时间】:2020-05-14 02:55:48 【问题描述】:

我想创建一个对象并通过标头发送 JWT 令牌。如果我跳过授权,它工作得很好。但是,一旦启用访问限制,我就会收到 CORS 错误或“拒绝访问”消息。

api调用

  editMediaObject(data): Observable<any> 
    var url = `$ApiServerUrl/edit_mo`;
    url = encodeURI(url);
    var headers = 
      "Content-Type": "application/x-www-form-urlencoded", 
      "Authorization": "..."  // Just the token, hardcoded for testing
      
    return from(this.httpAdvanced.post(url, data, headers)).pipe(map(res => res.data));
  

edit_mo.php

    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");
    header("Access-Control-Allow-Methods: POST, OPTIONS, GET");
    header("Access-Control-Max-Age: 3600");
    header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

    include_once '../users/validate_token.php';

    if ($validate_check) 

validate_token.php

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

include_once '../config/core.php';
include_once '../libs/php-jwt-master/src/BeforeValidException.php';
include_once '../libs/php-jwt-master/src/ExpiredException.php';
include_once '../libs/php-jwt-master/src/SignatureInvalidException.php';
include_once '../libs/php-jwt-master/src/JWT.php';
use \Firebase\JWT\JWT;

$headers = apache_request_headers();
if (isset($headers['Authorization'])) 
    $jwt = $headers['Authorization'];
 else 
    $jwt = "";


if($jwt)

    try 
        $decoded = JWT::decode($jwt, $key, array('HS256'));
        http_response_code(200);    
        $validate_check = TRUE;     
    

 catch (Exception $e)

    http_response_code(401);
    echo json_encode(array(
        "message" => "Access denied.",
        "error" => $e->getMessage()
    ));
    $validate_check = FALSE;



else

    $validate_check = FALSE;

    // set response code
    http_response_code(401);

    // tell the user access denied
    echo json_encode(array("message" => "Access denied."));

?>

我是否正确添加了标题?我需要更改标题设置中的某些内容吗?

【问题讨论】:

究竟是什么错误? CORS 已阻止以下请求 [...] 【参考方案1】:

我遇到了完全相同的问题,我找到了一个解决方案,可以帮助您克服错误。但是,我不确定这是否是最佳解决方案。它基本上使您可以从任何来源发送。这段代码不是我写的,不幸的是我不记得我在哪里得到它,在应得的地方给予赞扬。

如果有人有更好的解决方案,我也有兴趣听听。

这至少会让你摆脱可怕的错误:

header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS,DELETE,PUT');
header("Content-Type: application/json; charset=UTF-8");
header("Authorization: *");

// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) 
    header("Access-Control-Allow-Origin: $_SERVER['HTTP_ORIGIN']");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day


// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') 

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers:        $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']");

    exit(0);

【讨论】:

以上是关于通过标头进行 JWT 授权引发 CORS 错误的主要内容,如果未能解决你的问题,请参考以下文章

axios 授权标头/CORS 错误

添加授权标头时出现CORS错误

Angular 和 Laravel 授权标头 CORS 错误

如何在授权标头中将带有 fetch 和 cors 的 JWT 令牌发送到 Express 服务器?

使用带有 RS256 加密的 express-jwt 在应用程序路由上解码 JWT 令牌会引发未经授权的错误

将 Angular 与 JWT 的 Spring Boot 连接时出现 CORS 错误