5

In my unit test, I have a user for whom I generate a token:

$tokenString = $this->user->createToken('PHPunit', ['example'])->accessToken;

How can I afterward delete this user's token?

6 Answers 6

5

This is what I do when a user logged out.

public function logout() {
    Auth::user()->tokens->each(function($token, $key) {
        $token->delete();
    });

    return response()->json('Successfully logged out');
}

This code will remove each token the user generated.

1
  • 2
    "message": "Trying to get property 'tokens' of non-object",
    – MH Fuad
    Jul 3, 2020 at 12:22
3

I think something like this can revoke the token:

$this->user->token()->revoke()

Based on this link.

4
  • 1
    "message": "Undefined property: App\\Http\\Controllers\\AuthController::$user",
    – MH Fuad
    Jul 3, 2020 at 12:22
  • 1
    @MHFuad, don't you do some research before adding your comments here on SO? Jul 9, 2020 at 13:28
  • 1
    @VishalParkash. yes, i have
    – MH Fuad
    Jul 10, 2020 at 4:50
  • 1
    @MHFuad Ok, but the kind of error message you are posting are very easy to fix if you do some research. Jul 10, 2020 at 14:20
3

Laravel Sanctum documentation stated 3 different ways to revoke tokens. you can find it here.
but for most cases we just revoke all user's tokens via:

// Revoke all tokens...
auth()->user()->tokens()->delete();

note: for some reason intelephense gives an error saying tokens() method not defined but the code works fine. Hirotaka Miyata found a workaround here.
so the over all logout method can be something like this:

public function logout()
{
    //the comment below just to ignore intelephense(1013) annoying error.
    /** @var \App\Models\User $user **/
    $user = Auth::user();
    $user->tokens()->delete();

    return [
        'message' => 'logged out'
    ];
}
2

the best working solution is this

public function logout(LogoutRequest $request): \Illuminate\Http\JsonResponse
    {
        if(!$user = User::where('uuid',$request->uuid)->first())
            return $this->failResponse("User not found!", 401);

        try {
            $this->revokeTokens($user->tokens);

            return $this->successResponse([

            ], HTTP_OK, 'Successfully Logout');

        }catch (\Exception $exception) {
            ExceptionLog::exception($exception);

            return $this->failResponse($exception->getMessage());
        }

    }

    public function revokeTokens($userTokens)
    {
        foreach($userTokens as $token) {
            $token->revoke();
        }
    }
1
public function __invoke(Request $request)
{
    $request->user()
        ->tokens
        ->each(function ($token, $key) {
            $this->revokeAccessAndRefreshTokens($token->id);
        });

    return response()->json('Logged out successfully', 200);
}

protected function revokeAccessAndRefreshTokens($tokenId) {
    $tokenRepository = app('Laravel\Passport\TokenRepository');
    $refreshTokenRepository = app('Laravel\Passport\RefreshTokenRepository');

    $tokenRepository->revokeAccessToken($tokenId);
    $refreshTokenRepository->revokeRefreshTokensByAccessTokenId($tokenId);
}
1
1

The problem with these answers is, you are deleting all the tokens if the same user has 2 or more sessions opened in different browsers/devices.

I think it's better to use

$request->user()->currentAccessToken()->delete();

So, this is the code I'm using in my API:

    public function logout()
    {
         
        auth()->user()->currentAccessToken()->delete();
    
        return ['message' => 'Desconexión exitosa'];
    
    }

It's possible also to delete an specific token

$user->tokens()->where('id', $tokenId)->delete();

Documentation here: https://laravel.com/docs/10.x/sanctum#revoking-tokens

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.