Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 467
Dave Cruise Avatar asked Jul 22 '19 05:07

Dave Cruise


People also ask

Which is better JWT or Passport in laravel?

The "tymondesigns/jwt-auth" is a PHP Laravel implementation of the JWT protocol. On the other hand, Passport also uses JWT by default plus a huge extra, a complete Oauth2 implementation. Regarding the functionality, as I said they both use JWT thus you can use whichever you like to authentication via tokens.

What is the difference between sanctum and Passport in laravel?

Chatty Cathy @vincent15000 Passport is an OAuth server implementation, and used to offer OAuth authorisation for your application. Sanctum is an authentication library for “simpler” token-based authentication for clients that need it (i.e. mobile apps) but also offers cookie-based authentication for SPAs.

How do I stop multiple logs in laravel?

Step:1 Create a new Laravel 5.7 Project in users, migration table add one extra filed. if you already migrate users table then you need to add one extra field in the user table. After that migrate table in the database using this following command. In your Laravel application folder, LoginController.

How does laravel Passport authentication work?

Laravel Passport is an easy way to set up an authentication system for your API. As a Laravel package, it uses an OAuth2 server to perform authentication, creating tokens for user applications that request to interface with the API it protects, and only granting them access if their tokens are validated.


1 Answers

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

Add these events/listeners to your EventServiceProvider

'Laravel\Passport\Events\AccessTokenCreated' => [
    'App\Listeners\RevokeExistingTokens',
],

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.

like image 64
atymic Avatar answered Sep 20 '22 03:09

atymic