简体   繁体   中英

How to keep/pass authenticated user session to other domain in Laravel

I have a multi tenancy build with Laravel. Now I have a system (main) website

main.com

where users can register.

After registration a tenant (subdomain) website is created and they are getting redirected to a new subdomain

tenantB.main.com .

Of course the Session is then deleted and they are not logged in anymore. I am trying to keep the session but the only solution I have found so far is to change the SESSION_DOMAIN in session.php config to

SESSION_DOMAIN=.main.com

The session will then remain on all subdomains but different tenants should not share their sessions. With that change if I login to tenantB.main.com I am also authenticated on tenantA.main.com which is not what I want.

Another approach I want to try is to send the session data when redirecting to the tenant subdomain ( https://laravel.com/docs/7.x/redirects#redirecting-with-flashed-session-data ):

redirect($this->redirectPath())->with('auth', 'abc')

But here I am stuck. How can I pass the current session? Or is that a totally wrong approach?

I would simply use a cookie. The information is best stored on the client side. That way the client is responsible for providing their own identification.

It is then the responsibility of your authentication middleware to check if the user has permission to access the current tenant subdomain.

Chances are laravel already is configured to use cookies for authentication. In that case, all you will have to do is to implement your own guard!

Auth::extend('tentantAuth', function ($app, $name, array $config) {
    new TenantAuth(Auth::createUserProvider($config['provider']));
});

The TenantAuth class would then simply need to implement Illuminate\Contracts\Auth\Guard in order to be usable.

You can than use the extended authentication by updating your auth.php config file to use the driver 'tenantAuth'.

More information can be found under https://laravel.com/docs/7.x/authentication#adding-custom-guards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM