Search code examples
laravellaravel-sanctum

Laravel Sanctum with multiple login


Good day, I have a Laravel 8 application with a login page handled by Sanctum. I have to let the users login with the same username and password. How can I do it? I think that is something with the RedirectIfAuthenticated middleware but I don't know how I can update it.

This is a part of my .env file, I don't know if it could be useful:

BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DRIVER=local
QUEUE_CONNECTION=sync
#SESSION_DRIVER=file
SESSION_DRIVER=cookie
SESSION_LIFETIME=120

Tried to change the RedirectIfAuthenticated middleware but it goes in 401 error when I try to login with the same user as an authenticated one.


Solution

  • Hi Andrea i hope you have a good day , if you are using a laravel session auth and you want to allow the same user to login from multiple devices at the same time (as you mentioned in the comments) you need to adjust the default laravel auth configuration

    go to config/session.php and make sure you have expire_on_close => false

    'driver' => env('SESSION_DRIVER', 'file'),
    

    'lifetime' => env('SESSION_LIFETIME', 120),

    'expire_on_close' => false,

    so the session do not expired when the browser closed

    2- middleware

    by defaul laravel session managment middlware startSession ensures that only one user can have an active session at at time the only solution that can fix that is to create a new middleware and implement it into kernel

    php artisan make:middleware AllowMultipleSessions //to create custom middleware
    

    //your custom middleware

    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Support\Facades\Auth;
    
    class AllowMultipleSessions
    {
        public function handle($request, Closure $next, ...$guards)
        {
            foreach ($guards as $guard) {
                if (Auth::guard($guard)->check()) {
                    // this check if the user already logged in so it gonna let him login normally
                    return $next($request);
                }
            }
            return $next($request);
        }
    }
    

    3- register your middleware into kernel

    protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\AllowMultipleSessions::class,
        \Illuminate\Session\Middleware\AuthenticateSession::class,
    ],
    ];
    

    there is, i hope it works well for you , if you have questions feel free to reply here