I need to redirect a user after successful auth to its own sub-domain like
company.test.com
from test.com
The auth page opens on test.com
and when I get response for successful auth I get the user's sub-domain name from the database. So company name xyz
should redirect to xzy.test.com
, That part is already done.
The issue is the session of the user. I am saving the authenticated user data into redux and when pages refreshes/redirects to the subdomain it loses the user data.
All I can think of is that I should pass the authenticated user id
along with sub-domain like xyz.test.com/encrypted-user-id
to a route and I will get that user id on the back-end and will decrypt it and will force user login without asking for password again.
My question is that... is there an alternate way? If no, Is this a feasible way to solve this
Yes, there is an alternate, and more correct way to solve your question.
I'll try to answer in two parts: first enabling cookies between root- and sub-domains, and second how to do this in Laravel.
Make cookies available between root and sub-domains:
When receiving cookie headers, a browser can be instructed to share the cookie across subdomains. This is achieved by adding the domain to the Set-Cookie
header.
Set-Cookie: user=JohnDoe; domain=testdomain.com
As of RFC-6265, the above syntax will tell the browser that cookies set on test.com
should be made available to all subdomains (i.e. a.test.com
, xyz.test.com
). For a more detailed explanation see this answer here on SO.
Set cookies to be available on subdomains in Laravel:
According to Laravel responses
documentation the cookie
function accepts all arguments accepted by php's [setcookie][4]
function (look at path
and domain
arguments).
As an example, for a one off you could write:
$path = '/'; // make cookie available on all paths
$domain = "test.com"; // according to rfc6265 make available on root and subdomains
return $response($content)->cookie($name, $value, $minutes, $path, $domain);
Another way, for sharing all cookies across the root and subdomains comes from JacobBennet's snippet. The suggestion there is to set the desired value of the domain
variable in config/session.php
. Then, all (!) cookies will be available to subdomains.
The frontend side (React) should not do anything particular, besides "redirecting".