Skip to content

Laravel passport prevent user to login together with the same credential

I was using Laravel Passport to allow my mobile to call laravel api for using laravel authentication.

I found a problem recently which is laravel passport allow the same user to login from multiple devices. Is there any solution for me to prevent the same user to login with other devices at the same time?

I have found a way to logout with Laravel Passport but I do not know if it is the best way if I use

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

whenever a user is trying to login.

Advertisement

Answer

You can hook the AccessTokenCreated event, and then inside your listener you can revoke any existing tokens.

Add these events/listeners to your EventServiceProvider

'LaravelPassportEventsAccessTokenCreated' => [
    'AppListenersRevokeExistingTokens',
],

Then create a listener using php artisan make:listener RevokeExistingTokens

Then inside the handle function:

$user = User::find($event->userId);

$user->tokens()->offset(1)->get()->map(function ($token) {
    $token->revoke();
});

This will delete all of the users tokens except the one that was just created.

User contributions licensed under: CC BY-SA
8 People found this is helpful