Laravel - JWT Auth The token could not be parsed from the request

From your description, I checked source file of JWT Auth.

In class Tymon\JWTAuth\JWTAuth line 191 - 219 , there are two functions:

/**
 * Parse the token from the request.
 *
 * @param string $query
 *
 * @return JWTAuth
 */
public function parseToken($method = 'bearer', $header = 'authorization', $query = 'token')
{
    if (! $token = $this->parseAuthHeader($header, $method)) {
        if (! $token = $this->request->query($query, false)) {
            throw new JWTException('The token could not be parsed from the request', 400);
        }
    }

    return $this->setToken($token);
}

/**
 * Parse token from the authorization header.
 *
 * @param string $header
 * @param string $method
 *
 * @return false|string
 */
protected function parseAuthHeader($header = 'authorization', $method = 'bearer')
{
    $header = $this->request->headers->get($header);

    if (! starts_with(strtolower($header), $method)) {
        return false;
    }

    return trim(str_ireplace($method, '', $header));
}

Check the logic of them, I believe your request header is not properly provided.

if (! $token = $this->parseAuthHeader($header, $method)) { // all your get method not passed this step
   if (! $token = $this->request->query($query, false)) { // all your post method stucked here 
       throw new JWTException('The token could not be parsed from the request', 400);
   }
}

A properly formatted header looks like this :

http POST http://${host}/api/v1/product/favorite/111 "Authorization: Bearer ${token}"

That's all I can offer to you, hope it will help you through your thoughts. If it won't you can still debug those two functions.


I had the same issue on ec2 amazon AMI Linux php7.2 apache2.4 but token get generated in apache request headers but was not visible in Laravel request header so add this code in middleware this will work only on your server but may not work on localhost.

 $headers = apache_request_headers();
 $request->headers->set('Authorization', $headers['authorization']);

JWT middleware

    try {
            $headers = apache_request_headers(); //get header
            $request->headers->set('Authorization', $headers['authorization']);// set header in request

            $user = JWTAuth::parseToken()->authenticate();
        } catch (Exception $e) {
            if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){
                return response()->json(['status' => 'Token is Invalid']);
            }else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){
                return response()->json(['status' => 'Token is Expired']);
            }else{
                return response()->json(['status' => 'Authorization Token not found']);
            }
        }

Tags:

Php

Jwt

Laravel 5