首页 > 解决方案 > 通过标头进行 JWT 授权引发 CORS 错误

问题描述

我想创建一个对象并通过标头发送 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));
  }

编辑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) {

验证令牌.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."));
}
?>

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

标签: javascriptphptypescripthttpjwt

解决方案


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

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

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

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);
}

推荐阅读