Search code examples
phplaravelsession-cookieslaravel-9

How do I make different Laravel application installed on different subdomains of the same domain use the same user authentication system?


So I have mydomain.com with a laravel 9.x application that works as my main/master app. I also have subdomain.mydomain.com with a different Laravel application and purpose. But I would like to not make users have to log back in each time. Both applications are on the same server and have access to each others database. I have no problem sharing the model and programming.

My question is how can I have the SESSION Cookie automatically work for them both as I know CORS policies allow setting cookies over all subdomains and root domain.

I am assuming I need to use the same Application key for both, and edit the scope? Will it work or do I have to manually write some code to get the SESSION data find the user in the DB and manually log them in?

Any help would be appreciated.


Solution

  • So I was able to make this workbeautifully and easily with the following procedure: Make sure the environment variables in the .env for both installations have the same identical settings for:

    #APP_KEY is used to encrypt the session data so must be the same
    APP_KEY=base64:'YOUR KEY ' 
    #SESSION_COOKIE must be the same, this is normally not set and defaults to APP_NAME+"_session' which is a problem if your apps have different names
    SESSION_COOKIE=laravel_session
    #The SESSION_DOMAIN defaults to null which causes the CORS scope to limit to the subdomain level, in my testing must start with leading dot.
    SESSION_DOMAIN=.rootdomain.com
    

    In my case I also changed the hard coded config/session.php variables to:

    'http_only'=>false,//not necessary but helpful in such applications
    'samesite'=>'lax',//newer laravel will allow you to set 'none' but beware of security issues
    

    Now the only thing left is to make sure your application logic can share the same user base, I recommend one of the following:

    1. Share the same database table, you can set your DB Connection in your Model/User.php to a different database if you have access to the other aoolications DB
    2. Create a MySQL VIEW that generates the table based on the other user table if possible
    3. If above not possible you can create a one-to-one relationship as app1.users.id=app2.app1_user_id