5

I have a Larvel API that uses Tymon\JWTAuth to authenticate the user.

It is working fine.

For some reasons I have also a non-guarded route in web.php:

Route::get('myroute', 'MyController@mymethod');

The code of MyController@mymethod is the following:

$user = JWTAuth::toUser($request->input('token'));

// I tried also this:
// JWTAuth::setToken($request->input('token'));
// $user = JWTAuth::authenticate();

And I call the route using this url in the browser: /myroute?token=eyJ0eXAiOiJKV1QiLCJhbGci....

The problem is that I have an exception in JWT.php:

Tymon \ JWTAuth \ Exceptions \ JWTException A token is required

JWT.php

protected function requireToken()
{
    if (! $this->token) {
        throw new JWTException('A token is required');
    }
}

How can I decode the token that is passed as URL parameter and not in the header of the request?

Fabry
  • 1,498
  • 4
  • 23
  • 47

3 Answers3

1

I solved it using this code:

use Namshi\JOSE\SimpleJWS;

$secret = config('jwt.secret');
$jws = SimpleJWS::load($token);
if (!$jws->isValid($secret)) {
   return response()->json([], 401); // unauthorized
} 
$payload = $jws->getPayload();
$account = Account::find($payload["account"]["id"]);

However I would have preferred to use directly JWTAuth

Fabry
  • 1,498
  • 4
  • 23
  • 47
1

Instead of

$user = JWTAuth::toUser($request->input('token'));

Use

$user = $this->jwt->User();
johannchopin
  • 13,720
  • 10
  • 55
  • 101
m yadav
  • 1,783
  • 2
  • 11
  • 13
1

If you are using jwt-auth dev, the toUser method in old version will drop the error like above, try this:

// Get the currently authenticated user
$user = auth()->user();

If the user is not then authenticated, then null will be returned.

Tai Ly
  • 306
  • 4
  • 17