How to login from central domain to subdomain in angular using JWT?

Viewed 1018

I want to implement a feature in which there is a central login site lets say: https://example.com , and when user enter login credentials in this page and select from dropdown on which sub domain user wants to log into, the user gets logged into that subdomain like https://abc.example.com.

I am using MEAN stack and jwt token for authentication. JWT implementation is applied in standard way in which first: request is sent to "/authenticate" and then token is returned which will be stored in browser local storage.

I have successfully done one site authentication ie. login from https://example.com and logging user in that domain, but now
I want to implement like this flow =>

On login page of https://example.com :

  1. User can select an option from drop down in which subdomain to login
  2. After that user enters login credentials ( these credentials can be different or same for all subdomains )
  3. User gets redirected to dashboard page of that subdomain ( with JWT token stored in the local storage of that selected sub domain )

Above is the flow I want to be implemented but can be changed if other flow achieves the same result

I have searched questions and blogs regarding this topic:
I have gone through SSO ... but that is not what exactly I want; because SSO is like login in one subdomain and it gets logged in everywhere else... but I want to login from a single login page to subdomain's dashboard page based on user selection.

How I have thought of implementing this (not working) :
I will first send "/authenticate" request to https://example.com with parameter like
{ username: "alice", password: "****", subDomainUrl: "https://abc.example.com"}
My nodejs backend will authenticate and return me the JWT token. Now I will redirect to that subdomain(https://abc.example.com) and send this token from https://example.com to https://abc.example.com and somehow it will get stored in this subdomain's(https://abc.example.com) localstorage. After it is stored in local storage I can easily do my other work.

So how to implement this? Is the above approach practical; if then how to properly do it? What is the best way to implement these kind of architectures? Any help will be great, Thanks!

1 Answers

I suggest you first send /authenticate request from https://example.com/. It will be validated by nodejs backend and then generate JWT token and redirect to the new subdomain including token.

http.get('*',function(req,res){  
    res.redirect('https://abc.example.com?token='+JWTtoken);
})

You can fetch the token from the subdomain and store in your local storage. Further, you can use this token for your api authentication.

Related