我正在使用Passport和NodeJS Express,Connect。会话存储是 RedisStore。我正在使用Forcedotcom策略。
当我对我的 Express 服务器进行 REST 调用时,我总是在 req.session 的"护照"部分看到一个空白。此外,req.user 是未定义的:
{ cookie: ,
_expires: Tue Oct 29 2013 07:38:47 GMT+0000 (UTC),
httpOnly: true,
domain: '.DOMAIN' },
passport: {} }
但是,用户正在我的套接字对象socket.handshake.user上设置。
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);
},
success: function(data, accept) {
accept(null, true);
}
}));
在身份验证期间,对我存储在 Redis 中的用户对象进行护照序列化和反序列化:
passport.serializeUser(function( user, done ) {
done( null, user.id);
});
passport.deserializeUser(function( id, done ) {
redis.hget("usersf:"+id, "data", function(err, data) {
done( null, JSON.parse(data) );
});
});
高速连接中间件:
var sessionStore = new RedisStore({
client :redis,
host: rtg.hostname,
port: rtg.port,
db: redisAuth[0],
pass: redisAuth[1],
prefix: 'appsess:'
});
appSecure.use(allowCrossDomain);
appSecure.use(express.cookieParser());
appSecure.use(express.bodyParser());
appSecure.use(express.methodOverride());
appSecure.set('port', port);
appSecure.use(express.session({ secret: expressSecret, store: sessionStore, key:'expressSid', cookie: { maxAge : 604800000, domain:'.DOMAIN'}}));
appSecure.use(passport.initialize());
appSecure.use(passport.session());
appSecure.use(appSecure.router);
appSecure.use(express.static(__dirname + '/public'));
appSecure.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
重读本文后,我意识到会话对象上的 cookie 变量为空,这可能表示客户端存在问题。查看我的客户端AngularJS REST服务,我意识到参数WithCredentials设置为false。将此设置为 true 会导致发送会话 cookie,并且用户由 req.user 上的 Passport 设置。
myApp.factory('RESTService',
function ($http) {
return {
get:function (url, callback) {
return $http.get(url, {withCredentials:true}).
success(function (data, status, headers, config) {
callback(data);
}).
error(function (data, status, headers, config) {
console.log("failed to retrieve data");
});
}
};
}
);