2013-04-24 175 views
2

我一直在挣扎几天,我取得了一些很好的进展,但是我无法让我的会话工作得很好。为什么我的req.user在加载时始终为空?

我已经成功地使用Passport来与Facebook进行身份验证。当我用FB按钮点击我的登录时,会话完全加载,我的req.user对象都准备好了,但在我看来,我应该只需要做一次。

我知道护照保存了一个cookie。我已经查阅并看到了工作。

我想检测用户是否已登录我的索引页的负载,但是当我加载页面时,req.user对象始终为空,我的passport.deserializeUser方法永远不会调用来加载它(如果我点击进入FB按钮的日志,它确实会被调用)。

所以我的问题是,你如何告诉护照页面加载检查cookie并加载用户会话,如果有的话?


更新 - 好了,对于那些在日后发现这个问题,我只想去了什么,我在这里学到(感谢你们谁评论)。希望它能帮助其他人。

我习惯了无论服务器在哪里都能存在的.NET cookies。 Node.js和护照不在同一个前提下工作。默认情况下,node.js使用内存存储来保持其会话。当您关闭终端/命令行中的节点(每次更改服务器代码时必须执行此操作),存储器Cookie cookie信息将被重置,因此与其关联的任何cookie都没有意义。

为了解决这个问题,我安装了Redis(http://cook.coredump.me/post/18886668039/brew-install-redis)并将它挂上了我的店铺(http://www.hacksparrow.com/use-redisstore-instead-of-memorystore-express-js-in-production.html)。

这将在Azure上工作,这是我计划的生产服务器,因此一切正常。


好的,这里有一些代码。我不知道哪些部分要忍受...

这是server.js

/** 
* Module dependencies. 
*/ 

var express = require('express') 
, app = express() 
, partials = require('express-partials') 
, http = require('http') 
, server = http.createServer(app) 
, io = require('socket.io').listen(server) 
, routes = require('./routes') 
// facebook 
, passport = require('passport') 
, facebookStrategy = require('passport-facebook').Strategy 
// custom stuff 
, urlCommand = require('./middleware/UrlCommand') 
, azureCommand = require('./middleware/AzureCommand') 
, userCommand = require('./middleware/UserCommand'); 

// Ports 
var port = process.env.port; 

if (isNaN(port)) 
    port = 3000; 

server.listen(port); 

//allows the use of Layouts 
app.use(partials()); 

passport.serializeUser(function(user, done) { 
    done(null, user.RowKey); 
}); 

passport.deserializeUser(function (id, done) { 
    console.log("deserialize"); 
    userCommand.findByID(id, function (err, user) { 
     done(err, user); 
    }); 
}); 

// Configuration 
app.configure(function() { 
    app.set('views', __dirname + '/views'); 
    app.set('view engine', 'jade'); 
    app.use(express.cookieParser()); 
    app.use(express.bodyParser()); 
    app.use(express.session({ secret: 'SECRET!' })); 
    app.use(express.methodOverride()); 
    app.use(passport.initialize()); 
    app.use(passport.session()); 
    app.use(app.router); 
    app.use(express.static(__dirname + '/public')); 
}); 

app.configure('development', function(){ 
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); 
}); 

app.configure('production', function(){ 
    app.use(express.errorHandler()); 
}); 

// Facebook 
passport.use(new facebookStrategy({ 
    clientID: CLIENT, 
    clientSecret: "SECRET", 
    callbackURL: "http://localhost:3000/auth/facebook/callback" //DEV 
}, 
    function (accessToken, refreshToken, profile, done) { 
     userCommand.findOrCreate(profile.id, profile.name.givenName, profile.name.familyName, profile.emails[0].value, accessToken, function (error, user) { 
      return done(null, user); 
     }); 
    } 
)); 

// Routes 
app.get('/', routes.index); 
app.get('/auth/facebook', passport.authenticate('facebook', { scope: 'email' })); 
app.get('/auth/facebook/callback', passport.authenticate('facebook', { successRedirect: '/', 
                    failureRedirect: '/login' })); 

// Sockets 
io.sockets.on('connection', function (socket) { 
    // when the client emits 'sendURL', this listens and executes 
    socket.on('sendURL', function (data) { 
     console.log('sendURL called: ' + data); 
     urlCommand.AddURL(data); 

     // we tell the client to execute 'processURL' 
     io.sockets.emit('urlComplete', data); 
    }); 
}); 

console.log("Express server listening on port %d in %s mode", port, app.settings.env); 

index.js

exports.index = function (req, res) { 
    console.log(req.user); // ALWAYS NULL 
    res.render('index', { title: 'Express' }) 
}; 

UserCommand

var azureCommand = require('../middleware/AzureCommand'); 
var tableService = azureCommand.CreateTableService(); 

function findByID(id, callback) { 
    console.log('FindByID'); 

    tableService.queryEntity('user', 'user', id, function (error, entity) { 
     console.log('Found him: ' + entity.Email); 
     callback(error, entity); 
    }); 
} 

function findOrCreate(id, first, last, email, accessToken, callback) { 
    var user = { 
     PartitionKey: 'user' 
     , RowKey: id 
     , First: first 
     , Last: last 
     , Email: email 
     , AccessToken: accessToken 
    } 

    tableService.insertEntity('user', user, function (error) { 
     callback(null, user); 
    }); 
} 

exports.findByID = findByID; 
exports.findOrCreate = findOrCreate; 

这是我的输出日志显示,当我输出我的会议...

node server.js 
info - socket.io started 
Express server listening on port 3000 in development mode 
{ cookie: 
    { path: '/', 
    _expires: null, 
    originalMaxAge: null, 
    httpOnly: true }, 
    passport: {} 
} 
debug - served static content /socket.io.js 
+1

这听起来像你可能对你的会话cookie不正确的到期,但请出示代码(ESP您的应用程序和Passport配置),否则我只是在猜测。没有代码的 – robertklep 2013-04-24 06:53:53

+0

不可能告诉你什么是错的。你检查了[示例](https://github.com/jaredhanson/passport-facebook/tree/master/examples/login)附带护照-Facebook – balazs 2013-04-24 07:16:07

+0

你写*“如果我点击登录到FB按钮它会被称为“*关于'deserializeUser'。你打电话给那个按钮时会调用哪条路线? 'deserializeUser'从来就不是为'/'路由调用的,或者它不起作用?由于你没有处理'FacebookStrategy'回调中的错误,这可能是一个问题吗? – robertklep 2013-04-24 15:09:48

回答

2

的问题是在你的serializeUserdeserializeUser功能。

正如你注意到没有,当你点击FBlogin按钮deserializeUser被称为第一和唯一的一次 - 其实这就是所谓的与已通过serializeUser功能以前只返回前id。如果此时无法通过id找到用户,则passport.user不会保存到会话中。

因此,在以下请求中passport.deserializeUser根本不会被调用,因为express.session不会使用护照的用户标识填充req.session

综上所述:你需要检查,如果你的serializeUser返回一个id相比,可以理解和您deserializeUser反序列化。

FYI:正确req.user对象的身份验证的用户应该是这样的:

{ 
    cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true }, 
    passport: { user: 51772291b3367f0000000001 } 
} 
+0

所以我把一个console.log看看我的序列化方法是否被调用......它不是,除非我点击我的FB按钮。当我点击FB按钮时,它会被调用,然后我的反序列化被调用,并且一切正常。另一个实验告诉我,如果我关闭浏览器并返回,会话仍然有效。如果我重启我的服务器,它就消失了。这让我觉得我的cookie基于会话。我如何更新cookie护照制作,使其持续时间超过一个会话? – David 2013-04-24 22:39:14

+0

供参考:这是我的cookie的输出。 Cookie:{“cookie”:{“originalMaxAge”:35999999,“expires”:“2013-04-25T08:48:38.994Z”,“httpOnly”:true,“路径”:“/”},“护照”: { “用户”: “775119337”}}。我在这篇文章的基础上添加了MaxAge,但它没有帮助。 http://stackoverflow.com/questions/15016551/node-js-express-passport-cookie-expiration – David 2013-04-24 22:52:13

+1

@David因为你没有使用会话存储,Express将默认使用'MemoryStore'来存储会话,这意味着一旦你的服务器重新启动,会话就消失了。您应该使用持久性存储(如[connect-mongo](https://github.com/kcbanner/connect-mongo)),或者使用[基于cookie的会话](http://expressjs.com/ api.html#cookieSession)。 – robertklep 2013-04-25 06:35:52