'Retrieve user by Sanctum plainTextToken
How to retrieve the 'logged in' user from a Sanctum token.
For logging in I have the following method
public function login(Request $request)
{
if (Auth::attempt($request->toArray())) {
/* @var User $user */
$user = $request->user();
$token = $user->createToken('web-token')->plainTextToken;
return response()->json([
'user' => $user,
'token' => $token,
], Response::HTTP_OK);
}
}
Now for logging out I use a custom method.
public function logout(Request $request)
{
dd($request->user()); // <- Always returns null
}
I want to revoke the token, but I don't know how to retrieve the currently logged in user. Obviously for logging out I send the Authorization header with the Bearer and plainTextToken as value.
Solution 1:[1]
for sure you have first add token in bearer token
and to get user out of sanctum middleware now token is optional
$user = auth('sanctum')->user();
than log out
if ($user) {
$user->currentAccessToken()->delete();
}
note : this delete only current token
if u need all tokens use
foreach ($user->tokens as $token) {
$token->delete();
}
Solution 2:[2]
Since you're sending the bearer/token to the Logout url you can try to override the logout
function of the AuthenticatesUsers
:
/**
* Log the user out of the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
$this->guard()->logout();
$request->user()->tokens()->delete();
return redirect('/');
}
Solution 3:[3]
simply add the route within middleware('auth:sanctum') grouped routes then from inside the targeted function you can get user like this auth()->user() or if you just want to log out the user you can revoke token like this $request->user()->currentAccessToken()->delete();
Solution 4:[4]
If you don't use the default Sanctum middleware, you can get the user from the plain text token as follow:
use \Laravel\Sanctum\PersonalAccessToken;
/** @var PersonalAccessToken personalAccessToken */
$personalAccessToken = PersonalAccessToken::findToken($plainTextToken);
/** @var mixed $user */
$user = $personalAccessToken->tokenable;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mohamed elshazly |
Solution 2 | Makdous |
Solution 3 | Muhammad Almoayad |
Solution 4 | tomloprod |