Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

javascript - Express session with different cookie domain per request?

I have a situation where an app can be accessed from multiple different domains. For instance, foo.com and bar.com could both in theory point to my app. Additionally, their subdomains can also point to my app, so for instance red.foo.com and blue.foo.com. I'm using Express cookie sessions, and my initialization code for the session looks like that:

app.use(express.session({
    secret: "secret",
    cookie: {
        domain: ".foo.com"
    },
    store: new MongoStore({
        db: db
    })
}));

That works well for when users go through foo.com or any of it's subdomains, but bar.com won't work. I need to have both at once. Ideally, I would set it to a different domain per request, but I'm not sure how I would do that. My requests are highly asynchronous and if I just set it for the whole app at every request, I fear it might not work when two calls come in at once.

Is this at all possible? Does anyone have any ideas to solve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's what you do:

  • write a middleware your app can use in place of the default express.session middleware
  • in that middleware, based on the host request header instatiate and configure on instance of the express session middleware per domain, and then actually execute the middleware function appropriate for this request

pseudocode

var mwCache = Object.create(null);
function virtualHostSession(req, res, next) {
  var host = req.get('host'); //maybe normalize with toLowerCase etc
  var hostSession = mwCache[host];
  if (!hostSession) {
    hostSession = mwCache[host] = express.session(..config for this host...);
  }
  hostSession(req, res, next);
  //don't need to call next since hostSession will do it for you
}

app.use(virtualHostSession);

My requests are highly asynchronous and if I just set it for the whole app at every request, I fear it might not work when two calls come in at once.

Absolutely you cannot do that. It will be utterly incorrect.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...