Search code examples
laravelcookiesremember-me

Rename Laravel Remember Cookie Prefix remember_web_*?


Is there a way to rename Laravel's remember cookie prefix "remember_web_*"?

I have 3 Laravel projects on the same server, can be accessed by IP address, ports distinguish the projects. However, because of cookies are shared between ports, all projects read all cookies, every project can distinguish its own session cookies, but remember token cookies can't be distinguished. So only one project's session can be remembered at the same time.

Is there a way to rename Laravel's remember cookie prefix "remember_web_*"?


Solution

  • You'd have to create your own SessionGuard which extends from the original since there is no option to define this cookie name. It might be worth a PR for the original framework though.

    Step 1: create an override for the original SessionGuard:

    <?php
    
    namespace App\Guards;
    
    use Illuminate\Auth\SessionGuard;
    
    class MySessionGuard extends SessionGuard
    {
        public function getRecallerName()
        {
            // The original class does:
            // `return 'remember_'.$this->name.'_'.sha1(static::class);`
            // which is the same for every app.
    
            // Return your own cookie name:
            return 'remember_me_some_app';
        }
    }
    

    Step 2: add the guard to the bootstrap:

    use App\MySessionGuard;
    use Illuminate\Auth\EloquentUserProvider;
    // SomeServiceProvider.php
    public function boot() {
        Auth::extend(
            'my_session_guard',
            function ($app) {
                $provider = new EloquentUserProvider($app['hash'], config('auth.providers.users.model'));
                $guard = new MySessionGuard('my_session_guard', $provider, app()->make('session.store'), request());
                $guard->setCookieJar($this->app['cookie']);
                $guard->setDispatcher($this->app['events']);
                $guard->setRequest($this->app->refresh('request', $guard, 'setRequest'));
                return $guard;
            }
        );
    }
    

    Step 3: define the new guard in config/auth.php:

    'guards' => [
        'web' => [
            'driver' => 'my_session_guard',
            'provider' => 'users',
        ],
    ]
    

    When logging in with remember-me checked, the new cookie name should now be used.