我在 data.domain.com 有一个 NodeJS express 服务器,而我的 AngularJS 客户端位于 subdomain.domain.com。我正在使用护照/快递在服务器上创建会话。然后我的客户端尝试连接到同一服务器上的 socket.io。我在 socket.io 连接上收到 403(禁止)。
我认为这是一个跨域问题。我已经在 express 服务器上启用了 COR。我正在使用我的服务器 data.domain.com 中的 TLD 设置一个 cookie,即 express cookie 域配置是 .domain.com。
我检查了我的会话 cookie 是否在客户端上设置 - 'expressSid' 与 TLD .domain.com。当我注释掉开始 io.set("authorization"...
一切都在 HTTPS 下运行。我正在使用 RedisStore 进行会话存储。
Passport.io / socket.io 配置:
io.configure(function () {
io.set('transports', ['xhr-polling']);
io.set('polling duration', 10);
io.set('log level', 1);
io.set("authorization", passportSocketIo.authorize({
cookieParser: express.cookieParser, //or connect.cookieParser
key: 'expressSid', //the cookie where express (or connect) stores its session id.
secret: expressSecret, //the session secret to parse the cookie
store: sessionStore, //the session store that express uses
fail: function(data, accept) { // *optional* callbacks on success or fail
accept(null, false); // second param takes boolean on whether or not to allow handshake
},
success: function(data, accept) {
accept(null, true);
}
}));
});
快速配置:
var allowCrossDomain = function(req, res, next) {
var oneof = false;
if(req.headers.origin) {
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Credentials', true);
oneof = true;
}
if(req.headers['access-control-request-method']) {
res.header('Access-Control-Allow-Methods', req.headers['access-control-request-method']);
oneof = true;
}
if(req.headers['access-control-request-headers']) {
res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
oneof = true;
}
if(oneof) {
res.header('Access-Control-Max-Age', 60 * 60 * 24 * 365);
}
// intercept OPTIONS method
if (oneof && req.method == 'OPTIONS') {
res.send(200);
}
else {
next();
}
};
appSecure.configure(function(){
appSecure.use(allowCrossDomain);
appSecure.use(express.cookieParser(expressSecret));
appSecure.use(express.bodyParser());
appSecure.use(express.methodOverride());
appSecure.use(org.expressOAuth({onSuccess: '/home', onError: '/oauth/error'})); // <--- nforce middleware
appSecure.set('port', port);
});
appSecure.configure('production', function(){
appSecure.use(express.errorHandler());
appSecure.use(express.session({ secret: expressSecret, store: sessionStore, key:'expressSid', cookie: { domain:'.domain.com'}}));
appSecure.use(passport.initialize());
appSecure.use(passport.session());
appSecure.use(appSecure.router);
appSecure.use(express.static(__dirname + '/public'));
});