簡體   English   中英

為什么在React中,我的axios API調用具有包含承載的授權標頭 <token> 但未獲得授權並顯示401錯誤

[英]Why in React, my axios API call has Authorization Header which contains Bearer <token> but not being authorized and gives 401 error

我正在對我的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" } 

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM