我在我的项目中第一次实施tymondesigns / jwt-auth。 我成功生成令牌。但是要获得经过身份验证的用户有问题。它返回user_not_found错误。
这里一步一步地给我的代码片段
令牌生成代码:
public function authenticate(Request $request)
{
$user = User::where('username', $request->username)->where('password', md5($request->password))->first();
if(empty($user)){
return response()->json(['error' => 'invalid_credentials'], 401);
}
try{
$token = JWTAuth::fromUser($user);
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['error' => 'could_not_create_token'], 500);
}
return response()->json(compact('token'));
}
获取经过身份验证的用户代码:
我在查询字符串中传递了token
。
public function getAuthenticatedUser()
{
try {
if (! $user = JWTAuth::parseToken()->authenticate()) {
return response()->json(['user_not_found'], 404);
}
} catch (TokenExpiredException $e) {
return response()->json(['token_expired'], $e->getStatusCode());
} catch (TokenInvalidException $e) {
return response()->json(['token_invalid'], $e->getStatusCode());
} catch (JWTException $e) {
return response()->json(['token_absent'], $e->getStatusCode());
}
// the token is valid and we have found the user via the sub claim
return response()->json(compact('user'));
}
此代码返回此结果["user_not_found"]
一些重要说明
我的users
表主键是user_id
这就是我更改2个文件的原因
User
模型中添加了protected $primaryKey = 'user_id';
config/jwt.php
文件更改'identifier' => 'user_id'
我也做了一些调试。在这里,我分享这个 我打印查询日志并找到此查询日志
array:1 [
0 => array:3 [
"query" => "select * from `users` where `users`.`user_id` is null limit 1"//user_id is null. I think here is the problem
"bindings" => []
"time" => 3.94
]
]