Tymon JWT user_not_found-Laravel 5.1 [英] Tymon JWT user_not_found - Laravel 5.1
问题描述
我正在为移动应用程序构建一个api,并且正在使用JWT对用户进行身份验证.我正在尝试在Laravel 5.1中实现它.
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.
我不断收到错误消息:{"error":"user_not_found"}
每当我使用由authenticate方法提供给我的令牌时.
I keep getting the error: {"error":"user_not_found"}
whenever I use the token that was given to me by the authenticate method.
我的过程:
- 使用
Auth::attempt($credentials)
对用户进行身份验证
- 使用
$user = User::where('user_id', Auth::user()->user_id)->first();
从数据库获取用户
-
使用
- 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
但是当尝试使用令牌对用户进行身份验证时,它将引发错误{"error":"user_not_found"}
.
But when trying to authenticate the user using the token, it throws the error {"error":"user_not_found"}
.
我的routes.php:
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']);
});
如果我取出中间件组,则可以访问/users
路由.
我认为这是在Tymon\JWTAuth\Middleware
命名空间的GetUserFromToken
类中的某处发生的,因为那是列出错误user_not_found
的唯一位置.
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
.
我的数据库使用user_id
,而不仅仅是id
作为主键,这可能是问题所在吗?
My database uses user_id
, not just id
as primary keys, could this be the issue?
推荐答案
最后我明白了.
我进入了发布JWTAuthServiceProvider
时创建的config/jwt.php
文件,然后将identifier
更改为Users表的主键(因为user
设置设为App\User
,我的主键是用户模型中的user_id
.
I went into the config/jwt.php
file that was created when publishing the JWTAuthServiceProvider
and then I changed the identifier
to the primary key of my Users table (as the user
setting is set to App\User
, my primary key is user_id
in the User model).
'identifier' => 'user_id' // somewhere around line 79
它奏效了.
这篇关于Tymon JWT user_not_found-Laravel 5.1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!