[英]Tymon JWT user_not_found - Laravel 5.1
I am building an api for a mobile app, and I am using JWT to authenticate users.我正在为移动应用程序构建 api,并且我正在使用 JWT 来验证用户。 I am trying to implement it in Laravel 5.1.
我正在尝试在 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.每当我使用由身份验证方法提供给我的令牌时,我都会收到错误消息:
{"error":"user_not_found"}
。
My process:我的流程:
Auth::attempt($credentials)
Auth::attempt($credentials)
验证用户$user = User::where('user_id', Auth::user()->user_id)->first();
$user = User::where('user_id', Auth::user()->user_id)->first();
从数据库中获取用户$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"}
.但是当尝试使用令牌对用户进行身份验证时,它会抛出错误
{"error":"user_not_found"}
。
My routes.php:我的路线.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.如果我取出中间件组,我可以访问
/users
路由。 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
.我认为它发生在
Tymon\\JWTAuth\\Middleware
命名空间的GetUserFromToken
类中的某个地方,因为这是唯一列出错误user_not_found
。
My database uses user_id
, not just id
as primary keys, could this be the issue?我的数据库使用
user_id
,而不仅仅是id
作为主键,这可能是问题吗?
Finally I got it.最后我明白了。
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).我进入了在发布
JWTAuthServiceProvider
时创建的config/jwt.php
文件,然后我将identifier
更改为我的 Users 表的主键(因为user
设置被设置为App\\User
,我的主键是user_id
在用户模型)。
'identifier' => 'user_id' // somewhere around line 79
And it worked.它奏效了。
You need a login route, that creates a session first.您需要一个登录路由,它首先创建一个会话。 Then get the user.
然后获取用户。
Route::post('sessions/create', ['uses' => 'Auth\JwtAuthController@authenticate']);
Route::get('sessions/user', ['uses' => 'Auth\JwtAuthController@getAuthenticatedUser']);
Try the following code in your controller:在控制器中尝试以下代码:
/**
* Authenticate by credentials
*/
public function authenticate()
{
$credentials = request()->only('email', 'password');
try {
if ( !$token = JWTAuth::attempt($credentials) ) {
return $this->error('invalid-credentials', 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return $this->error('could-not-create-token', 500);
}
return response()->json(compact('token'));
}
/**
* Get the user by jwt token, or return an error
*
* @return Response
*/
public function getAuthenticatedUser()
{
try {
if ( !$user = JWTAuth::parseToken()->authenticate() ) {
return $this->error('user-not-found', 204);
}
} catch (TokenExpiredException $e) {
return $this->error('token-expired', 401);
} catch (TokenInvalidException $e) {
return $this->error('token-invalid', 401);
} catch (JWTException $e) {
return $this->error('token-absent', 400);
}
// the token is valid and we have found the user via the sub claim
return response()->json(compact('user'));
}
/**
* Error formatter
*
* @param string $message
* @param integer $statuscode
*
* @return \Illuminate\Http\JsonResponse
*/
private function error($message, $statuscode = 401)
{
return response()->json(['error' => $message], $statuscode);
}
If your code is correct, then also if your getting output:如果您的代码正确,那么如果您获得输出:
{
"error": "invalid_credentials"
}
dd($request->only('email', 'password'));
or dd($credentials);
或
dd($credentials);
// output should be like this.. // 输出应该是这样的..
array:2 [
"email" => "myemail@myemail.com"
"password" => "test123"
]
dd($token);
// output should be: false // 输出应该是:false
1) Inside of app/Http/Kernel.php
make sure \\App\\Http\\Middleware\\VerifyCsrfToken::class
is commented out. 1) 在
app/Http/Kernel.php
确保\\App\\Http\\Middleware\\VerifyCsrfToken::class
被注释掉。 2) Inside config/jwt.php
make sure you have the identifier set to the primary key of your Users table. 2) 在
config/jwt.php
确保将标识符设置为用户表的主键。
'identifier' => 'userid'
// default is set to 'id' 'identifier' => 'userid'
// 默认设置为 'id'
On line number: 70 Change Model Location where your saved model(User)在线编号:70 更改您保存模型的模型位置(用户)
for example: App\\Model\\Myuser\\User
例如:
App\\Model\\Myuser\\User
and和
On line number: 71 Change Table Name to what you have set in your model(User)在线编号:71 将表名称更改为您在模型中设置的名称(用户)
for example: protected $table = 'my_user';
例如:
protected $table = 'my_user';
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\Myuser\User::class,
'table' => 'my_user'
],
Try it: In User model write the single line: protected $primaryKey = 'user_id'
;试试看:在用户模型中写一行: protected
$primaryKey = 'user_id'
;
Example:例子:
class User extends Authenticatable
{
use Notifiable;
protected $table = 'my_user';
protected $primaryKey = 'user_id';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.