3

I'm developing a nodejs web application, in that I have multiple subdomains like domain.com, sub1.domain.com, sub2.domain.com etc.

if user logs in to sub1.domain.com and gets redirected to domain.com or sub2.domin.com it will give as not logged in,

How can I maintain this session across sub-domains and in main-domain?

I'm using express, nodejs, mongodb.

app.use(session({
    secret: "secrete key",
    store: new MongoStore({
        db: "session-db"
    })
}));

I tried setting up like this, didn't work:

app.use(session({
    secret: "secret key",
    cookie: { domain:'.yourdomain.com'}, // here I used '.localhost'
    store: new MongoStore({
        db: "session-db"
    })
}));
gvlasov
  • 14,781
  • 17
  • 61
  • 99
Sudhakar Reddy
  • 309
  • 5
  • 11

1 Answers1

2

What you're asking is not recommended, eg: Share cookie between subdomain and domain

What you really want, is Single Sign On (SSO).

There are two ways to do SSO in Node (that I'm aware of, there are probably other tools out there that I've never heard of):

  • Write the code yourself. Basically what you'll do is setup a domain like login.mysite.com which you redirect users to for authentication. Once they're authenticated, you generate a JWT and then redirect the user to othersubdomain.mysite.com/?token=xxx where xxx is your JWT. This way, your othersubdomain project can verify the JWT is valid, and log the user in there as well.
  • Use a library like express-stormpath with their SSO feature (described here). This is a paid service (it has a free plan though), which does this stuff for you 100%.

I'm the author of the express-stormpath library, so I'm a bit biased, but in general, SSO stuff is actually quite complex, and there are a lot of potential issues implementing things incorrectly with it.

Community
  • 1
  • 1
rdegges
  • 27,994
  • 16
  • 73
  • 100
  • 1
    Why is it not recommended? – Calebmer Jul 29 '15 at 14:44
  • Are you sure that use othersubdomain.mysite.com/?token=xxx as share way is secure? This token will be in history browser. – user1710825 Aug 05 '16 at 15:15
  • @user1710825 you can use make the token 1 time useable – FooBar Aug 27 '16 at 18:16
  • I think that the best way is to use a JWT as session token. The session tokens not need to be only for one session (you can use JWT extra params for manage some extra security like IP or version of password). This token can be shared between subdomains (or domains if you want) using postmessage (libraries like https://github.com/zendesk/cross-storage/ can help in this) – user1710825 Aug 28 '16 at 20:02