Using Express and Node, how to maintain a Session across subdomains/hostheaders

房东的猫 提交于 2019-11-27 03:41:00

First of all to allow browser to make cross-domain requests you need to set headers on server side. This solution works for normal request as well as AJAX. In your express configure function:

Express 4.0:

var express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');

var app = express();

app.use(cookieParser());
app.use(session({
    secret: 'yoursecret',
    cookie: {
        path: '/',
        domain: 'yourdomain.com',
        maxAge: 1000 * 60 * 24 // 24 hours
    }
}));
app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Origin', req.headers.origin);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
    next();
});

Access-Control-Allow-Origin can be set to '*' if no cross-domain cookies exchange for sessions needed. To have cookies and session shared cross-domain you need to set specific Access-Control-Allow-Origin to actually domain where request is made from, that's why req.headers.origin - is perfect for that.

Using domain it wont work well on localhost - so make sure you disable it in development environment, and enable on production. It will enable shared cookies across top and sub domains.

This is not all. Browsers it self won't send cookies over cross domain requests, and this have to be forced. In jQuery you can add extra parameter in $.ajax() request:

xhrFields: { withCredentials: true }

For non jQuery, just have XHR constructor and set this parameter:

xhr.withCredentials = true;

And you are ready to do cross-domain with shared session.

Did you make sure you have your cookies set to the top-level domain so it can be read by all subdomains? Then it's just a matter or persisting your session data in memory, a db, whatever as usual. I don't have my dev machine up and running, but it'll be something like this in your app.configure().

app.use(express.cookieParser());

app.use(express.session({  
  key: 'A_SESSION_KEY',   
  secret: 'SOMETHING_REALLY_HARD_TO_GUESS',   
  store: new express.session.MemoryStore,  
  cookie: {  
    path     : '/',  
    domain   : 'yourdomain.com',  
    httpOnly : true,  
    maxAge   : 1000*60*60*24*30*12    //one year(ish)  
  }   
}));

Note: If using Express 4 and the new cookie-session module, the code looks like

{ 
  secret: <session_secret> , 
  store: <session store> , 
  domain: '.domain.com',
}

This bit me, but the API has changed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!