Expire time express and redis session

2019-06-03 08:42发布

问题:

I'm using express and redis to keep the session live on my system. I having some problems to set the maxAge on the sessionCookie. By the default I read that is 24hrs, but that's a long time to keep it live. I would like to set like 30 min and then logout the user, I changed for 1min to see if it works but nothing happens, the user still logged.

This is my session function:

module.exports.initSession = function(app, db) {
  app.use(session({
    saveUninitialized: true,
    resave: false,
    secret: config.sessionSecret,
    cookie: {
      maxAge: 30*10000,
      httpOnly: true,
      secure: Boolean(process.env.ssl) || true
    },
    key: config.sessionKey,
    store: new RedisStore({
      host: config.redis.host || 'localhost',
      port: config.redis.port || 6379,
      db: config.redis.database || 0,
      pass: config.redis.password || ''
    })
  }));
};

I also tried using ttl instead of maxAge but I get the same result. What could it be?

EDITED:

I using SEAN.JS and the files that content the session are this two: express.js and default environment.

回答1:

This is my configuration for sessions and it works.
I set the expiration time to 5 seconds for testing purposes.

app.use(session({
        store: new redisStore({
        host: 'localhost',
        port: 6379,
        client: redisClient,
        ttl: 5 // in seconds
    }),
    secret: 'this is secret',
    resave: false,
    saveUninitialized: true,
    // cookie: {maxAge: 5000}
}));

I set maxAge and it didn't work and when i set ttl it worked.

Note: I tested and found out that ttl is in second but maxAge is in milli seconds! (kinda weird)

you can log session data using a middleware like below to see if a passport object exists or not, if there is no passport object in sesssion data, user is logged out.

app.use((req, res, next) => {
    console.log('session:\n', req.session);
    next();
});