Nodejs + Passport.js + Redis:如何在Redis中存储会话

时间:2012-10-18 05:52:47

标签: node.js session redis passport.js

我已经阅读了这个主题Node.js + express.js + passport.js : stay authenticated between server restart,我需要完全相同的东西,但对于Redis。我使用了这样的代码:

var RedisStore = require('connect-redis')(express);
app.use(express.session({
    secret: "my secret",
    store: new RedisStore,
        cookie: { secure: true, maxAge:86400000 }
}));

它不起作用。要连接Redis,我使用connect-redis模块。我做错了什么?谢谢!

UPD :我没有收到任何错误。为了确保auth进程成功,我添加了log-line,然后执行。

function(email, password, done) {
    // asynchronous verification, for effect...
    process.nextTick(function() {
        findByEmail(email, function(err, user) {
            if (!user) {
                return done(null, false, {
                    message: 'Unknown user ' + email
                });
            }
            if (user.password != password) {
                return done(null, false, {
                    message: 'Invalid password'
                });
            }
            //just logging that eveything seems fine
            console.log("STATUS: User " + email + " authentificated succesfully");
            return done(null, user);
        })
    });
}));

启用express.logger()的日志是:

127.0.0.1 - - [Fri, 19 Oct 2012 05:49:09 GMT] "GET /ico/favicon.ico HTTP/1.1" 404 - "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4"
STATUS: User admin authentificated succesfully

假设auth / users / credentials / serializing / deserializing本身没有任何问题。问题只是护照无法设置cookie到Redis并阅读它。

3 个答案:

答案 0 :(得分:5)

我应该使用

cookie: { secure: false, maxAge:86400000 }

答案 1 :(得分:1)

尝试一下,而不是将express传递给const RedisStore pass会话。

const redis = require('redis');
const session = require('express-session');
const redisStore = require('connect-redis')(session);
const cookieParser = require('cookie-parser');
const app = require('../app');


app.app.use(cookieParser("secret"));


const rediscli = redis.createClient();


app.app.use(session({
    secret: 'secret',
    store: new redisStore({
        host: '127.0.0.1',
        port: 6379,
        client: rediscli,
        ttl: 260
    }),
    saveUninitialized: false,
    resave: false
}));

答案 2 :(得分:0)

明确设置商店会发生什么?即你的应用程序中的这些内容:

var redis = require('redis');
// This is host and port-dependent, obviously
var redisClient= redis.createClient(6379, 'localhost');

app.use(express.session({
    secret: 'your secret',
    /* set up your cookie how you want */
    cookie: { maxAge: ... },
    store: new (require('express-sessions'))({
        storage: 'redis',
        instance: redisClient
    })
}));