为什么在React中,我的axios API调用具有授权标头,其中包含Bearer <token>但未得到授权并给出401错误

时间:2019-03-23 12:54:22

标签: reactjs api jwt authorization axios

我正在对我的php API进行axios调用(当将有效令牌发送回API服务器时会显示用户数据),并在请求标头(连同Bearer作为前缀)和“网络”标签中发送有效的jwt令牌它表明我的令牌正在标头中发送,但仍然给我401错误,并返回“ jwt为空”的API错误消息...

我的用于提取用户数据(提供有效令牌时)的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"
}

1 个答案:

答案 0 :(得分: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");  }
    });