我一直在挣扎几天,我取得了一些很好的进展,但是我无法让我的会话工作得很好。为什么我的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
这听起来像你可能对你的会话cookie不正确的到期,但请出示代码(ESP您的应用程序和Passport配置),否则我只是在猜测。没有代码的 – robertklep 2013-04-24 06:53:53
不可能告诉你什么是错的。你检查了[示例](https://github.com/jaredhanson/passport-facebook/tree/master/examples/login)附带护照-Facebook – balazs 2013-04-24 07:16:07
你写*“如果我点击登录到FB按钮它会被称为“*关于'deserializeUser'。你打电话给那个按钮时会调用哪条路线? 'deserializeUser'从来就不是为'/'路由调用的,或者它不起作用?由于你没有处理'FacebookStrategy'回调中的错误,这可能是一个问题吗? – robertklep 2013-04-24 15:09:48