Bruno Ramalho
Bruno Ramalho

Reputation: 11

laravel jwt-auth Token is Invalid

I built an api in Laravel using tymondesigns/jwt-auth to authenticate users.

I followed the tutorial on github and the login is working correctly:

public function login() {
        if (!$token = JWTAuth::attempt(Input::only('email', 'password'))) {
            return response()->json(['error' => true], HttpResponse::HTTP_UNAUTHORIZED);
        }

        $user = User::where('email', Input::get('email'))->first();

        return response()->json(array(
            'user' => $user, 
            'token' => compact('token')['token'])
        );
    }

And for the response I got the token.

But every time I try to use the toke I got:

[
  "Token is invalid"
]

ie:

public function getUser() {
        $token = JWTAuth::getToken();
        return response()->json(JWTAuth::toUser($token));
    }

This is a GET to {{url}}/api/getUser with the header Authorization: Bearer {{token}}

my routes.php contains the following:

Route::group(array('prefix' => 'api'), function() {
    Route::post('/login', 'API\UserController@login');
    Route::get('/getUser', ['before' => 'jwt-auth', 'uses' => 'API\UserController@getUser']);
});

How can I make this working with the token? Am I missing something here?

UPDATE:

I got a token like this:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHA6XC9cL3NtYXJ0YXBwXC9hcGlcL2xvZ2luIiwiaWF0IjoxNDY2Mjc5ODUxLCJleHAiOjE0NjYyODM0NTEsIm5iZiI6MTQ2NjI3OTg1MSwianRpIjoiYjNkZjViZGNiMjQ2YWU0NzVlZDYwODQxMWFlZDNkMTAifQ.pqU0pWKVzmOel51ObyE9vKLk07tefh2lDE-fp-AOavE

After I check the token on https://jwt.io, I got invalid signature. Why I'm getting and invalid signature, and how can I make it valid?

Upvotes: 1

Views: 3394

Answers (3)

user8529149
user8529149

Reputation:

you can do it just like that:

    public function login() {
         if (!$token = JWTAuth::attempt(Input::only('email', 'password'))) {
            return response()->json(['error' => true], 
        HttpResponse::HTTP_UNAUTHORIZED);
       }

    $user = User::where('email', Input::get('email'))->first();

    return response()->json(array(
        'user' => $user, 
        'token' => compact(['token'])
    );
}

Upvotes: 0

suguna
suguna

Reputation: 811

Try this,

Define a constructor, so that you can get the user by using $this->jwtauth->toUser() through out that class with out repeatedly using JWTAuth $jwtauth in the function.

private $jwtauth;

public function __construct(JWTAuth $jwtauth)
{
    $this->jwtauth = $jwtauth;
}

public function getUser()
{
    $user = $this->jwtauth->toUser();
    return response($user);
}

Upvotes: 0

linuxartisan
linuxartisan

Reputation: 2426

Try this

public function getUser() {
  // set the token on the object

  JWTAuth::parseToken();

  // get the user from token
  $user = JWTAuth::parseToken()->authenticate();

  return response()->json(compact('user'));
}

Upvotes: 1

Related Questions