PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, September 5, 2022

[FIXED] How to disallow TTL refresh for sessions stored through Express-session?

 September 05, 2022     cookies, express-session, node.js, redis, session     No comments   

Issue

I have a couple requirements around session handling and I'm having trouble enforcing one.

Sessions need to:

  1. Expire in 30 mins if user has been inactive
  2. Expire in 8 hours from when user first logged on regardless of activity.

I was able to configure item 1 but not item 2. Every time a user is browsing application, the cookie is updated (with time+30mins) and sent back to the browser but at the same time the session storage TTL is also refreshed. The last part is what I need to stop.

I believe the TTL refresh is implemented as a feature from express-session. Session.touch() is called by the middleware but is there a setting that'll remove this action?

The stack: Node, express, express-session, connect-redis for session storage.

The configuration:

    app.use(session({
  store: new RedisStore({
    client: redis_client,
    ttl: 28800 // 8 hours
  }),
  secret: config.redis_session_secret,
  resave: false,
  saveUninitialized: false,
  cookie: {
    path: '/',
    httpOnly: true,
    secure: false,
    maxAge: 30 * 60 * 1000 //mins * seconds * milliseconds. session cookie will expire every 30 mins 
  }, 
  rolling: true
}));

Solution

I don't think option 2 is a supported feature of express session. So, instead you can just add a property to each session that indicates the time it was started and then every 10 minutes or so (probably on an interval timer), query for all sessions where that property is older than 8 hours and remove them from the database.

You could instead implement middleware that checks the session expiration on every request and removes the session if it find the session is older than 8 hours.

You should be aware that implementing this behavior could cause a user to lose their session in the middle of using your app (which is why it is not typically implemented this way).



Answered By - jfriend00
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing