我用的是Nodejs Express的Passport,连接。会话存储是redistore。我用的是forcedotcom策略。
当我对我的express服务器进行rest调用时,我总是在req.session的passport部分看到一个空白。此外,req.user未定义:

{ cookie: ,
_expires: Tue Oct 29 2013 07:38:47 GMT+0000 (UTC),
httpOnly: true,
domain: '.DOMAIN' },
passport: {} }

但是,用户正在我的sockets对象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序列化和反序列化:
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服务,我意识到带凭证的参数设置为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");
                });
        }
    };
}
);

关于node.js - 未在Express session 上设置Passport用户,但可在套接字握手中使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19512035/

10-16 13:03