4
votes

I'm making axios call to my php API (which shows user data when a valid token is sent back to API server) and sending a valid jwt token in request header (along with Bearer as prefix) and in the Network's tab its showing that my token is being sent in the header but still it gives me 401 error and returns the Error msg of API that "jwt is empty"...

my API to fetch user data (when valid token is provided) is on http://localhost/Auth/api/validate.php

and client side is on http://localhost:3000

This API is in php and works perfectly fine on Postman. But gives me 401(unauthorized) when I call it in react. I searched this error and everyone says that u should have token in the Request header, I do have it but its not being read by the server and server considers it null so sends me unauthorized error. Please Please help me someone!!!!!

here is the axios API call:

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

Response Headers

>  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

Request Headers:

> 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

Here is my 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"));
}
?>

EDIT I also tried sending the token without 'Bearer' prefix but it didnt work. On Postman I send a post request (in the body) to my server API like this(which works fine):

{
"jwt": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7IlZlbmRvcklEIjoiNTkiLCJDb21wYW55TmFtZSI6IkVub3VnaCIsIkNvbnRhY3RQZXJzb24iOiJlbm91Z2giLCJDb250YWN0Tm8iOiIzNDM0NCIsImVtYWlsIjoiZUBnbWFpbC5jb20ifX0.o4V6zu8AFBAMoJgRe_jvMoByDK3yDEiF_pxW4ttqpYQ"
}
1
is your browser sending a preflight options request? Check your browser network tabAmstel D'Almeida
are you reading jwt token from body or Header?Jibin Mathews
@AmstelD'Almeida Yes it is sending a preflight options and I solved that issue by redirecting the OPTIONS requests to a blank page which returns 200 status OK and then it sends my actual POST request for which it shows 401 errorYellowMinion
@JibinMathews in the Postman I sent the token from the body tab (just like I mentioned in the edit) so Should I also send the token in the body while doing API axios call in react? BTW thankssssa lot for your response.YellowMinion
@YellowMinion Looking at your php code, the JWT token should be sent in the body as a json and not header.Amstel D'Almeida

1 Answers

0
votes

The php code is expecting JWT token in the body. The token should be in a JSON as shown below.

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