Maintaining login session across subdomains in nod

2019-04-11 05:38发布

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"
    })
}));

1条回答
霸刀☆藐视天下
2楼-- · 2019-04-11 06:12

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.

查看更多
登录 后发表回答