jwt-auth icon indicating copy to clipboard operation
jwt-auth copied to clipboard

The token could not be parsed from the request

Open ulisescarreonalvarez opened this issue 6 years ago • 10 comments

Lumen: 5.6 JWT: 1.0.0-rc.2 SO: Mac/Ubuntu

I'm making a simple API with Lumen, i use the JWTAuth library to make the tokens.

My login looks like:

try
                {
                    $this->validate($request, [
                        'email'    => 'required|email|max:255',
                        'password' => 'required'
                    ]);
                    try 
                    {
                        if (!$this->token = $this->jwt->attempt($request->only('email', 'password'))):
                            throw new HttpResponseException(response()->json(['message' => 'Email/Contraseña invalidos'], JsonResponse::HTTP_UNPROCESSABLE_ENTITY));
                        endif;
                    } 
                    catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $e) 
                    {
                        throw new HttpResponseException(response()->json(['message' => 'Token expirado'], JsonResponse::HTTP_UNPROCESSABLE_ENTITY));
                    }
                    catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $e) 
                    {
                        throw new HttpResponseException(response()->json(['message' => 'Token invalido'], JsonResponse::HTTP_UNPROCESSABLE_ENTITY));
                    }
                    catch (\Tymon\JWTAuth\Exceptions\JWTException $e) 
                    {
                        throw new HttpResponseException(response()->json(['message' => 'Sin token'], JsonResponse::HTTP_UNPROCESSABLE_ENTITY));
                    }
                    return response()->json([
                        "token" => $this->token,
                        "email" => $this->jwt->user()->email,
                        "rfc" => $this->jwt->user()->rfc,
                        "nombre" => $this->jwt->user()->nombre,
                        "_uof" => $this->Cipher->EncryptCipher($this->jwt->user()->id),
                        "_rof" => $this->Cipher->EncryptCipher($this->jwt->user()->rfc)
                    ], 200);
                }
                catch(\Exception $error)
                {
                    throw new HttpResponseException(response()->json(['message' => 'Error al iniciar sesión el usuario'], JsonResponse::HTTP_UNPROCESSABLE_ENTITY));
                }

That returns my token that is set on a React Frontend App, when i try to validate the token with curl or postman on my local enviroment with:

try
        {
            $this->payload = $this->jwt->getPayload($this->jwt->getToken())->toArray();
            var_dump($this->payload);
        }
        catch(\Exception $error)
        {
            var_dump($error->getMessage());
        }

My request looks like:

curl -X POST \
http://localhost:8000/debtor/validateLogin/ \
-H 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9hcGltcGFsYS5yZWFsaG9zdC5jbG91ZFwvYXV0aFwvbG9naW4iLCJpYXQiOjE1MjcyODcyMTEsImV4cCI6MTUyNzI5MDgxMSwibmJmIjoxNTI3Mjg3MjExLCJqdGkiOiJyc3duZFh0NndzMXdhRGRvIiwic3ViIjoxLCJwcnYiOiI4N2UwYWYxZWY5ZmQxNTgxMmZkZWM5NzE1M2ExNGUwYjA0NzU0NmFhIiwibmFtZSI6IlVsaXNlcyBDYXJyZW9uIiwicmZjIjoiWEFYWDAxMDEwMTAwMCIsImF2YXRhciI6bnVsbH0.Ey1lMFYtSAE5f8pSrXjxnrMLGv2yOhl3DvwJo1qiTCI' \
-H 'Cache-Control: no-cache' \
-H 'Content-Type: application/json' \
-H 'Postman-Token: 29819986-830d-48f8-8724-25ce2fbf0af2' \
-d '{}'

The token is on the Header of the request but when i make the request it throw this error "A token is required".

I've change the .htaccess to :

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    #RewriteCond %{HTTP:Authorization} .
    #RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Fix authentication headers
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

But still doesn't work, any advice?

Regards

ulisescarreonalvarez avatar Jun 01 '18 20:06 ulisescarreonalvarez

I have the same issue on my configuration. Is there some fix for this?

jimmyd-be avatar Sep 09 '18 08:09 jimmyd-be

Same here. tymon/jwt-auth/src/JWTGuard.php

protected function requireToken()
{
    if (! $this->jwt->setRequest($this->getRequest())->getToken()) {
        throw new JWTException('Token could not be parsed from the request.');
    }
 
    return $this->jwt;
}

Datalink-Wouter avatar Dec 06 '18 15:12 Datalink-Wouter

Same here.

My trace problem if below....

image

jfeliubadalo avatar Mar 29 '19 23:03 jfeliubadalo

Did you manage to find a solution for this? I am getting the same error, just for 1 selected users over and over again.

gayanhewa avatar Aug 12 '19 07:08 gayanhewa

Same here, there is no way to handle this Exception and redirects user to login page?

felipesmendes avatar Jan 21 '20 14:01 felipesmendes

My two cents I changed logout function to this and call it with GET method

public function logout(Request $request) { if (! $user = auth()->setRequest($request)->user()) { return $this->responseUnauthorized(); } auth()->logout(); return $this->responseSuccess('Successfully logged out.'); }

marhyno avatar Apr 11 '20 23:04 marhyno

Is this still relevant? If so, what is blocking it? Is there anything you can do to help move it forward?

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.

stale[bot] avatar Dec 25 '20 17:12 stale[bot]

Estou com p mesmo problema, alguém ai conseguiu resolver, procurei já tem umas duas horas

Danielwebgit avatar May 03 '21 04:05 Danielwebgit

სეიმ გაიზ

Pickle99 avatar Aug 01 '22 13:08 Pickle99

# Handle Authorization Header
#RewriteCond %{HTTP:Authorization} .
#RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

the above worked for me for Lumen 7

bsadjetey avatar May 04 '23 17:05 bsadjetey