为什么在React中,我的axios API调用具有包含Bearer的Authorization Header 但没有被授权,并给出401错误

问题描述 投票:2回答:1

我正在对我的php API进行axios调用(当有效令牌被发送回API服务器时显示用户数据)并在请求头中发送有效的jwt令牌(以及Bearer作为前缀),并在Network的选项卡中显示我的令牌是在标题中发送但仍然给我401错误并返回API的错误消息“jwt为空”...

我的用于获取用户数据的API(在提供有效令牌时)位于http://localhost/Auth/api/validate.php

客户端在http://localhost:3000

这个API在php中,在Postman上完美运行。但是当我把它称为反应时,给我401(未经授权)。我搜索了这个错误,每个人都说你应该在Request标头中有令牌,我确实拥有它,但它没有被服务器读取,服务器认为它为null所以发送给我未经授权的错误。请帮帮我一个人!!!!!

这是axios API调用:

e.preventDefault();
const token = localStorage.getItem("jwttoken");

 axios.post('http://localhost/Auth/api/validate.php',token, {
headers: {
'Authorization' : 'Bearer '+token,
  'Accept': 'application/json, text/plain, */*',
   'Content-Type': 'application/json'
      }} )

.then(response =>
{
console.log(response.data);
console.log(response);
return response;
})
  .catch(error => {
  if (error) {
    console.log("Sorry.....Error");  }
    });

响应标题

>  Request URL: http://localhost/Auth/api/validate.php 
>  Request Method: POST 
>  Remote Address: [::1]:80 
>  Status Code: 401 Unauthorized
>  Referrer Policy: no-referrer-when-downgrade
> Accept: application/json; charset=UTF-8, */* 
> Access-Control-Allow-Credentials: true 
> Access-Control-Allow-Headers: Content-Type, Accept,  X-Auth-Token, Origin,  Authorization, Client-Security-Token, Accept-Encoding, X-Requested-With
> Access-Control-Allow-Methods: GET, PUT, POST, DELETE, HEAD, OPTIONS
> Access-Control-Allow-Origin: * 
> Access-Control-Exposed-Header: true
> Authorization Access-Control-Max-Age: 33600
>  Connection: Keep-Alive
> Content-Length: 34 
> Content-Type: application/json; charset=UTF-8, */*
> Date: Sat, 23 Mar 2019 12:33:00 GMT Keep-Alive: timeout=5, max=99
> Server: Apache/2.4.29 (Win32) OpenSSL/1.1.0g PHP/7.2.3 X-Powered-By:
> PHP/7.2.3

请求标题:

> Provisional headers are shown Accept: application/json, text/plain, */*
>Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7IlZlbmRvcklEIjoiNDQiLCJDb21wYW55TmFtZSI6IlRhZGEiLCJDb250YWN0UGVyc29uIjoiVGFkYSIsIkNvbnRhY3RObyI6Ijg3ODciLCJlbWFpbCI6InRhZGFAZ21haWwuY29tIn19.YmaD_VjMKYifWXd4DsRXRodVDpBy8zASLnIfgquCwLI

> Content-Type: application/json 
> Origin: http://localhost:3000 
> Referer: http://localhost:3000/profile 
> User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36


> Request Payload: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7IlZlbmRvcklEIjoiNDQiLCJDb21wYW55TmFtZSI6IlRhZGEiLCJDb250YWN0UGVyc29uIjoiVGFkYSIsIkNvbnRhY3RObyI6Ijg3ODciLCJlbWFpbCI6InRhZGFAZ21haWwuY29tIn19.YmaD_VjMKYifWXd4DsRXRodVDpBy8zASLnIfgquCwLI

这是我的API validate.php

<?php
// required headers//
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Content-Type: application/json; charset=UTF-8, */*");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Max-Age: 33600");
header("Content-Length: 144");
header("Accept: application/json; charset=UTF-8, */*");
header("Access-Control-Exposed-Header: Authorization");
header("Access-Control-Allow-Headers: Content-Type, Accept,  X-Auth-Token, Origin,  Authorization,  Client-Security-Token, Accept-Encoding, X-Requested-With");


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

// get posted data
$data = json_decode(file_get_contents("php://input"));

// get jwt
$jwt=isset($data->jwt) ? $data->jwt : "";

// if jwt is not empty
if($jwt){

    // if decode succeed, show user details
    try {
        // decode jwt
        $decoded = JWT::decode($jwt, $key, array('HS256'));

        // set response code
        http_response_code(200);

        // show user details
        echo json_encode(array(
            "message" => "Access granted.",
            "data" => $decoded->data
        ));

    }

        // if decode fails, it means jwt is invalid
    catch (Exception $e){

        // set response code
        http_response_code(401);

        // tell the user access denied  & show error message
        echo json_encode(array(
            "message" => "Access denied. Decode fails",
            "error" => $e->getMessage()
        ));
    }
}

// show error message if jwt is empty
//gggg
else{

    // set response code
    http_response_code(401);

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

编辑我也尝试发送没有'Bearer'前缀的令牌,但它没有用。在Postman上我发送一个帖子请求(在正文中)到我的服务器API这样(工作正常):

{
"jwt": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7IlZlbmRvcklEIjoiNTkiLCJDb21wYW55TmFtZSI6IkVub3VnaCIsIkNvbnRhY3RQZXJzb24iOiJlbm91Z2giLCJDb250YWN0Tm8iOiIzNDM0NCIsImVtYWlsIjoiZUBnbWFpbC5jb20ifX0.o4V6zu8AFBAMoJgRe_jvMoByDK3yDEiF_pxW4ttqpYQ"
}
reactjs api jwt authorization axios
1个回答
0
投票

php代码期待正文中的JWT令牌。令牌应该是JSON,如下所示。

const token = localStorage.getItem("jwttoken");

 axios.post('http://localhost/Auth/api/validate.php',{"jwt":token}, {
headers: {
  'Accept': 'application/json, text/plain, */*',
   'Content-Type': 'application/json'
      }} )

.then(response =>
{
console.log(response.data);
console.log(response);
return response;
})
  .catch(error => {
  if (error) {
    console.log("Sorry.....Error");  }
    });
© www.soinside.com 2019 - 2024. All rights reserved.