[英]Why is the request user null in my logout function?
I am implementing an Authentication api in Laravel using passport .我正在使用passport在 Laravel 中实施身份验证 api 。
I have implemented the login api, but there is a problem with logout api.我已经实现了登录api,但是注销api有问题。 My login code is working successfully:我的登录代码运行成功:
public function login(Request $request){
$request->validate([
'email'=> 'required|string|email',
'password'=> 'required|string',
'remember_me'=> 'boolean',
]);
$credentials= request(['email','password']);
if(!Auth::attempt(['email' => $request->email, 'password' => $request->password])){
return response()->json([
'message'=> 'Unauthorized'
],401);
}
Auth::attempt(['email' => $request->email, 'password' => $request->password]);
$user=$request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if($request->remember_me)
$token->expires_at= Carbon::now()->addWeek(1);
$token->save();
return response()->json([
'access_token'=>$tokenResult->accessToken,
'token_type'=>'Bearer',
'expires_at'=>Carbon::parse($tokenResult->token->expires_at)
->toDateTimeString()
]);
}
This works successfully, however, when I use the same bearer token to revoke the token of the user I am receiving the following exception:但是,当我使用相同的不记名令牌撤销用户的令牌时,这可以成功,我收到以下异常:
Call to a member function token() on null致电 null 上的成员 function token()
This is referring to the first line of the logout method below.这是指下面注销方法的第一行。
public function logout(Request $request){
$request->user()->token()->revoke();
return response()->json([
'message'=> 'Successfully logged out'
]);
}
Why is the output of $request->user()
null?为什么$request->user()
的 output 是 null?
Create a token for the authenticated user, not the guest user who made the request为经过身份验证的用户创建令牌,而不是发出请求的访客用户
$user= auth()->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->accessToken;
And when revoking并且撤销时
public function logout(Request $request)
{
auth()->user()->token()->revoke();
return response()->json([
'message'=> 'Successfully logged out'
]);
}
Hope this helps希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.