5

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.

Ezrab_
  • 825
  • 5
  • 19
  • 44

4 Answers4

6

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

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;
tomloprod
  • 7,472
  • 6
  • 48
  • 66
0

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('/');
}
Makdous
  • 1,447
  • 1
  • 12
  • 24
  • Sorry to clarify myself, I am not using the default logout url, but a custom one. Also if I dd $request->user() it returns null since there is no active user. – Ezrab_ Jul 01 '20 at 22:21
0

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