Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping auth-token between two subdomains

I have an Angular 7 web app with two different subdomains: sub1.myurl.com and sub2.myurl.com

They both have the same login endpoint and all the APIs inside look for auth token.

You can switch a 'namespace' inside the app, which in some cases forwards you from sub1 to sub2 domain and vice versa, which also means page refresh.

Currently I'm keeping my auth token in local storage. So in a scenario when user is redirected from sub1 to sub2, the local storage content changes and the auth-token will be lost.

I've read that cookies would be the solution for that, but once again there might be security issue.

I also tried using ngx-cookie-service but can't find a way to add general cookie that is available in localhost with no subdomains and also on production environments on sub1.myurl.com and sub2.myurl.com?

like image 242
raouaoul Avatar asked Sep 11 '25 03:09

raouaoul


1 Answers

Actually figured it out by myself. I'll post my solution here in case anyone ends up with the same problem.

   const loc = window.location;
   if (loc.hostname === 'sub1.myurl.com' || loc.hostname === 'sub2.myurl.com') {
      this.cookieService.set('token', session, null, '/', '.myurl.com', true);
   } else {
      this.cookieService.set('token', session);
   }

So based on window.location.hostname I set cookies differently. For production environment where I have to share cookies between subdomains, putting a dot (.) if front of domain parameter, makes it also applicable to subdomains of this domain.

like image 118
raouaoul Avatar answered Sep 13 '25 18:09

raouaoul