I have created two Mean.io apps in domain.com and in sub.domain.com respectively and everything works as expected in both but the problem is that the one in the subdomain (sub.domain.com) needs to know if the user is logged in the main app (domain.com).
I know that passport handles sessions and knows if user is logged in because it creates an user object in req for every request in express.js:
if (req.user) {
// logged in
} else {
// not logged in
}
The inconvenient here is that this approach works from within the domain but not outside. In other words, if I make a request to backend like this:
$http.get('/api/users/me').success(this.onIdentity.bind(this));
from domain.com, this will be populated with user data, but if I make the same request directly from the browser, for example, it returns null.
I need to understand how could I pass this information across domains? And if everytime this request $http.get('/api/users/me').success(this.onIdentity.bind(this));
is made, information is passed to backend?
I found the answer after some deep research.
Short answer: it is impossible using localStorage (data is only accesible by domain; not even for subdomains), which is the tool Mean.io now uses to store user information.
Long answer, every time, as long as you are logged in, you send a request to backend, angular intercepts the request before actually send it (this post explains this https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/) and adds an authorization header like this:
headers:
{
...
authorization: 'Bearer eyJhbGciOiJIUzI1NiJ9.JTdCJTIyX2lkJTIyOiUyMjU1ZDFjYmIxNDA..._rUsUBFxCQy3qqUGi9QGVD0YXCEk0',
...
}
which passport later employs to serialize user info into session and put it in req.user. The Bearer token is stored in localStorage and for that reason it's impossible to get it from outside the domain. The only way I came up with was with cookies with domain = '.domain.com'
so that every subdomain could read those cookies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With