Home > OS >  How can I logout and revoke all oauth tokens in laravel 8 api?
How can I logout and revoke all oauth tokens in laravel 8 api?

Time:10-17

The api I built with passport and laravel 8 does not logout by default.

I found a script, but it does not remove the entries in the oauth-access-tokens table

I added a function to the AuthController:

 
    public function logout(Request $request){
        $accessToken = auth()->user()->token();
        $token= $request->user()->tokens->find($accessToken);
        $token->revoke();
        return response(['message'=> 'Je bent uitgelogd'], 200);
    }

And added a path in api.php:

Route::post( 'logout', 'App\Http\Controllers\API\AuthController@logout')->middleware('auth:api'); 

When I try to logout with Postman, I get a success message, but the entry in the oauth-access-token table is not removed.

I intend to remove all tokens for the user, to log out from all devices

Can anyone tell me what I am doing wrong?

CodePudding user response:

Change the logout function to be like:

public function logout(Request $request){
    $user = Auth::user()->token();
    $user->revoke();
    return response(['message'=> 'Je bent uitgelogd'], 200);
}

This will log the user out from the current device where he requested to log out. If you want to log out from all the devices where he's logged in. Then do this instead:

use Laravel\Passport\RefreshToken;
use Laravel\Passport\Token;

public function logout(Request $request){
    $tokens =  $user->tokens->pluck('id');
    Token::whereIn('id', $tokens)->update(['revoked', true]);

    RefreshToken::whereIn('access_token_id', $tokens)->update(['revoked' => true]);

}

This will revoke all the access and refresh tokens issued to that user.

CodePudding user response:

SOLVED:

I used the following code:


use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

and the function:

public function logout(Request $request){
    Auth::user()->tokens->each(function($token, $key) {
        $token->delete();
    });
    return response(['message'=> 'Je bent uitgelogd'], 200);
   
} 

So nothing is revoked, but all the tokens are just deleted..

  • Related