3
votes

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.

3
Did you try Auth::user()?Makdous
@Makdous Yeah that returns null. Because there is no logged in user via session.Ezrab_

3 Answers

5
votes

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();
}
0
votes

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();

-1
votes

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('/');
}