NodeJS + Redis + Express + Passport Facebook身份验证失败

时间:2014-03-27 12:49:21

标签: node.js express node-redis passport-facebook

我遇到NodeJS和redis与护照facebook集成的问题。这是我的代码:

var express = require('express');
var engine = require('ejs').__express;
var app = express();
var mongo = require('mongodb');
var mongoose = require('mongoose');
var hanzi  = require('./modules/hanzi');
var session = require('express-session');
var passport = require('passport')
, FacebookStrategy = require('passport-facebook').Strategy
, RedisStore = require('connect-redis')(session)
, redis = require('redis')
, dbRedis = redis.createClient();

Server = mongo.Server,
Db = mongo.Db,
BSON = mongo.BSONPure;


app.configure(function () {

    var sessionStore = new RedisStore({
        client: dbRedis,
    });

    app.set('port', process.env.PORT || 8088);
    app.set('views', __dirname+'/views');
    app.engine('ejs', engine);
    app.use(express.favicon(__dirname + '/public/img/favicon.ico'));
    app.use( express.cookieParser() );
    app.use(express.session({
        secret: 'im your besta' ,
        cookie: {secure: true, maxAge:86400000},
        store: sessionStore
    }));
    app.use(express.logger('dev'));
    app.use(express.json());
    app.use(express.urlencoded());
    app.use('/public', express.static(__dirname + '/public'));
    app.use(passport.initialize());
    app.use(passport.session());
});

但是当我登录感谢facebook时,我找到了合适的用户,请使用done(null,oldUser);,但我的ensureAuthenticated()函数始终为false ...

你有什么想法吗?

提前致谢!

修改 序列化/反序列化

passport.serializeUser(function(user, done) {
                    console.log("serialize user");
                    console.log(user._id);
                    done(null, user._id);
                });

passport.deserializeUser(function(obj, done) {
                    console.log("deserialize user");
                    done(null, obj);
                });

passport.use(new FacebookStrategy({
                    clientID: "xxx",
                    clientSecret: "xxxx",
                    callbackURL: "http://myurl/auth/facebook/callback"
                },
                function(accessToken, refreshToken, profile, done) {

                    db.collection('fbs', function(err, collection) {
                        collection.findOne({fbId : profile.id}, function(err, oldUser) {
                            if(oldUser){
                                console.log("OK");
                                console.log(oldUser);
                                done(null,oldUser);
                            }else{
                                console.log("NEW USER");
                                var newUser = new FbUsers({
                                    fbId : profile.id ,
                                    email : profile.emails[0].value,
                                    name : profile.displayName
                                }).save(function(err,newUser){
                                    if(err) throw err;
                                    done(null, newUser);
                                });
                            }
                        });

                    });
                }
                ));

function ensureAuthenticated(req, res, next) {
    if (req.isAuthenticated()) { return next(); }
    res.redirect('/')
}

编辑2:添加redis日志

+1395994580.698685 (db 2) "setex" "sess:Od0RD3AcyIhTMUynnlDQobEr" "86400" "{\"cookie\":{\"originalMaxAge\":86400000,\"expires\":\"2014-03-29T08:16:20.698Z\",\"secure\":true,\"httpOnly\":true,\"path\":\"/\"},\"passport\":{}}"
+1395994582.099713 (db 2) "setex" "sess:OT1Rht88PPbeMDnKvYjMmGlC" "86400" "{\"cookie\":{\"originalMaxAge\":86400000,\"expires\":\"2014-03-29T08:16:22.099Z\",\"secure\":true,\"httpOnly\":true,\"path\":\"/\"}}"
+1395994582.102495 (db 2) "setex" "sess:nu6Pm2xb4SFpf8IPNFz7oBUa" "86400" "{\"cookie\":{\"originalMaxAge\":86400000,\"expires\":\"2014-03-29T08:16:22.102Z\",\"secure\":true,\"httpOnly\":true,\"path\":\"/\"}}"
+1395994582.104810 (db 2) "setex" "sess:qckQqsbZsEWCrpA1dJEvRdsa" "86400" "{\"cookie\":{\"originalMaxAge\":86400000,\"expires\":\"2014-03-29T08:16:22.104Z\",\"secure\":true,\"httpOnly\":true,\"path\":\"/\"}}"
+1395994582.109756 (db 2) "setex" "sess:WmXRkw2GKWx8DRz25RIwMOWJ" "86400" "{\"cookie\":{\"originalMaxAge\":86400000,\"expires\":\"2014-03-29T08:16:22.109Z\",\"secure\":true,\"httpOnly\":true,\"path\":\"/\"}}"
+1395994582.112338 (db 2) "setex" "sess:3WkCT4YqL1mpeyHXiBwjpWpR" "86400" "{\"cookie\":{\"originalMaxAge\":86400000,\"expires\":\"2014-03-29T08:16:22.112Z\",\"secure\":true,\"httpOnly\":true,\"path\":\"/\"}}"
+1395994582.117175 (db 2) "setex" "sess:yKaQ2Z5QJaC8UG1dw2q0sZMo" "86400" "{\"cookie\":{\"originalMaxAge\":86400000,\"expires\":\"2014-03-29T08:16:22.117Z\",\"secure\":true,\"httpOnly\":true,\"path\":\"/\"}}"
+1395994582.248297 (db 2) "setex" "sess:m2xlPaDlFCnVelxFnvmWEnKJ" "86400" "{\"cookie\":{\"originalMaxAge\":86400000,\"expires\":\"2014-03-29T08:16:22.248Z\",\"secure\":true,\"httpOnly\":true,\"path\":\"/\"}}"
+1395994582.964619 (db 2) "setex" "sess:XWQeeUCS7JUZTPzxZSMxqUpR" "86400" "{\"cookie\":{\"originalMaxAge\":86400000,\"expires\":\"2014-03-29T08:16:22.964Z\",\"secure\":true,\"httpOnly\":true,\"path\":\"/\"}}"
+1395994582.970229 (db 2) "setex" "sess:LqgRcHrnIaXfXVceHgdZ6FlN" "86399" "{\"cookie\":{\"originalMaxAge\":86399999,\"expires\":\"2014-03-29T08:16:22.969Z\",\"secure\":true,\"httpOnly\":true,\"path\":\"/\"}}"
+1395994588.902167 (db 2) "setex" "sess:qXO9gBrHu8vp64UyKYJHWcCq" "86400" "{\"cookie\":{\"originalMaxAge\":86400000,\"expires\":\"2014-03-29T08:16:28.900Z\",\"secure\":true,\"httpOnly\":true,\"path\":\"/\"},\"passport\":{}}"
+1395994590.304890 (db 2) "setex" "sess:JA4KfLN92wVIYrcOyhZeQw2O" "86400" "{\"cookie\":{\"originalMaxAge\":86400000,\"expires\":\"2014-03-29T08:16:30.304Z\",\"secure\":true,\"httpOnly\":true,\"path\":\"/\"},\"passport\":{\"user\":\"52de69b0c432647c5fc6309c\"}}"
+1395994590.690489 (db 2) "setex" "sess:Vc6Z6oLnnxGqqzItuEWpO8ab" "86400" "{\"cookie\":{\"originalMaxAge\":86400000,\"expires\":\"2014-03-29T08:16:30.690Z\",\"secure\":true,\"httpOnly\":true,\"path\":\"/\"},\"passport\":{}}"
+1395994591.582708 (db 2) "setex" "sess:XIud7BMHoPjJ0BFf6AMkrJV9" "86400" "{\"cookie\":{\"originalMaxAge\":86400000,\"expires\":\"2014-03-29T08:16:31.582Z\",\"secure\":true,\"httpOnly\":true,\"path\":\"/\"}}"
+1395994591.585150 (db 2) "setex" "sess:IlHl8a7QDp2g9UpXAmYHOk09" "86400" "{\"cookie\":{\"originalMaxAge\":86400000,\"expires\":\"2014-03-29T08:16:31.585Z\",\"secure\":true,\"httpOnly\":true,\"path\":\"/\"}}"
+1395994591.631536 (db 2) "setex" "sess:jeLL5UZkPXEeK8K3mbCaBwrl" "86400" "{\"cookie\":{\"originalMaxAge\":86400000,\"expires\":\"2014-03-29T08:16:31.631Z\",\"secure\":true,\"httpOnly\":true,\"path\":\"/\"}}"
+1395994591.634714 (db 2) "setex" "sess:xIgC6NKShHW8ewG8YGSCm0vn" "86400" "{\"cookie\":{\"originalMaxAge\":86400000,\"expires\":\"2014-03-29T08:16:31.634Z\",\"secure\":true,\"httpOnly\":true,\"path\":\"/\"}}"
+1395994591.638343 (db 2) "setex" "sess:SxfiYe5TBeUGrNQ4z3MPIBHe" "86400" "{\"cookie\":{\"originalMaxAge\":86400000,\"expires\":\"2014-03-29T08:16:31.638Z\",\"secure\":true,\"httpOnly\":true,\"path\":\"/\"}}"
+1395994591.953461 (db 2) "setex" "sess:JK0nt4aD0ycED0kjiAEPZEPD" "86400" "{\"cookie\":{\"originalMaxAge\":86400000,\"expires\":\"2014-03-29T08:16:31.953Z\",\"secure\":true,\"httpOnly\":true,\"path\":\"/\"}}"
+1395994591.987201 (db 2) "setex" "sess:B6TOzQWvBo8HiN55so28iL8X" "86400" "{\"cookie\":{\"originalMaxAge\":86400000,\"expires\":\"2014-03-29T08:16:31.987Z\",\"secure\":true,\"httpOnly\":true,\"path\":\"/\"}}"
+1395994592.033600 (db 2) "setex" "sess:BoQODHZ8kjgqczNAe7By8kEs" "86400" "{\"cookie\":{\"originalMaxAge\":86400000,\"expires\":\"2014-03-29T08:16:32.033Z\",\"secure\":true,\"httpOnly\":true,\"path\":\"/\"}}"
+1395994592.036671 (db 2) "setex" "sess:lmeCXBZUr0dw38iozFNOBayK" "86400" "{\"cookie\":{\"originalMaxAge\":86400000,\"expires\":\"2014-03-29T08:16:32.036Z\",\"secure\":true,\"httpOnly\":true,\"path\":\"/\"}}"

我不知道为什么我会添加这么多饼干......有什么想法吗?

1 个答案:

答案 0 :(得分:1)

serializeUser函数由护照提供的req.logIn函数使用。

req.login =
req.logIn = function(user, options, done) {
  if (typeof options == 'function') {
    done = options;
    options = {};
  }
  options = options || {};

  var property = 'user';
  if (this._passport && this._passport.instance) {
    property = this._passport.instance._userProperty || 'user';
  }
  var session = (options.session === undefined) ? true : options.session;

  this[property] = user;
  if (session) {
    if (!this._passport) { throw new Error('passport.initialize() middleware not in use'); }
    if (typeof done != 'function') { throw new Error('req#login requires a callback function'); }

    var self = this;
    this._passport.instance.serializeUser(user, this, function(err, obj) {
      if (err) { self[property] = null; return done(err); }
      self._passport.session.user = obj;
      done();
    });
  } else {
    done && done();
  }
};

可以调用此req.logIn函数以将序列化用户保留在会话中,从而进行登录。该函数由passport.authenticate函数自动调用,该函数在根据定义的策略获取用户后调用它,

创建护照策略为护照创建一个程序来查找您的用户,它不会自行执行登录。 isAuthenticated是错误的,因为登录永远不会发生。

因此,要为您的facebook身份验证策略创建身份验证路由,请在路由中添加类似的内容,

app.get('/auth/facebook', passport.authenticate('facebook', { state: 'SOME STATE' }));

现在转到此路线的护照将找到用户使用您的Facebook策略并自动为该用户执行登录。

假设你的facebook stragtegy没有错误..它应该工作得很好..