I am building an api for a mobile app, and I am using JWT to authenticate users. I am trying to implement it in Laravel 5.1.
I keep getting the error: {"error":"user_not_found"}
whenever I use the token that was given to me by the authenticate method.
My process:
- Authenticate the user using
Auth::attempt($credentials)
- Get the user from the db using
$user = User::where('user_id', Auth::user()->user_id)->first();
Set the Token for the user using
$token = ""; try { // attempt to verify the credentials and create a token for the user if (! $token = JWTAuth::fromUser($user)) { return response()->json(['error' => 'invalid_credentials'], 401); } } catch (JWTException $e) { // something went wrong whilst attempting to encode the token return response()->json(['error' => 'could_not_create_token'], 500); }
It is returning a token using this method:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOm51bGwsImlzcyI6Imh0dHA6XC9cL3BlZGxyLmRldlwvYXBpXC9sb2dpbiIsImlhdCI6MTQ0OTk2NDQ2NywiZXhwIjoxNDQ5OTY4MDY3LCJuYmYiOjE0NDk5NjQ0NjcsImp0aSI6IjJlMDMyMjA5MjMyZWM1MDVlY2I3YzE4ODFjNDk1MzFmIn0.tbO_fv4WDQ6WgiHtyYJAq2rjnOtaYPq85VO2ja2YVzw
But when trying to authenticate the user using the token, it throws the error {"error":"user_not_found"}
.
My routes.php:
Route::any('/login', ['as' => 'login', 'uses' => 'APIController@postLogin']);
Route::group(['middleware' => 'jwt.auth'], function() {
Route::any('/users', ['as' => 'users', 'uses' => 'UsersController@getUsers']);
});
If I take the middleware group out, I can access the /users
route.
I think it is happening somewhere in the GetUserFromToken
class in the Tymon\JWTAuth\Middleware
namespace as that is the only place that lists the error user_not_found
.
My database uses user_id
, not just id
as primary keys, could this be the issue?