Axedyson
Axedyson

Reputation: 279

What is the best practice way to manage user session cookie expiration?

I'm using express-session, connect-redis and ioredis to store the session and the user will have the redis key stored in a browser cookie. connect-redis resets the TTL every time the server is being interacted with, which means that right now with default settings the in-memory session will outlive the browser cookie at some point as the user interacts with the website. I would like to keep the user session alive and not show a popup to the user specifying that they should reauthenticate or that they will be logged out soon or something like that. How do big sites such as YouTube and Facebook keep user sessions alive? I've never experienced the sudden need to reauthenticate on youtube in years I think. So my question is how should cookie session expiration dates get handled with an emphasis on good user experience, and not sacrificing security?

My current idea is to simply just check when there is a certain amount of time equal to the time left before a cookie expires, and if that turns out to be true AND the user has just interacted with the website, reset the maxAge property on the cookie. In that way, if the user isn't going to interact with the website for more than that certain amount of time say 3 months, and the time left before the cookie expires is exactly 3 months, then the user will get logged out the next time the user visits the site after those 3 months. In other words, as long as the user keeps doing something on the website in intervals of less than 3 months, then they will always still be logged in and authenticated. What do you think about that? I could also set the rolling property to true, but I don't want to send session cookies with every authenticated request because of performance reasons. Also, I can't write to the cookie trying to increase its expiration date with client-side Javascript since I'm setting httpOnly to true.

Upvotes: 1

Views: 1797

Answers (1)

BGPHiJACK
BGPHiJACK

Reputation: 1397

To be honest, it's much easier then that. Imagine you have a remember me when you sign in, if that was untoggled, you'd change TTL to a day or few hours when session is created or you use the TTL you set by default.

You definitely want the sessions to forcefully expire, so these keys change up all the time and make any hijacking unlikely.

Below is how I set my redisStore up, I am lacking sync between two devices wanting a single account session but that's a topic for another time.

WEBAPP.use(SESSION({
    name: "WebSiteNameOrCookieName",
    store: new redisStore({
        client: client,
        ttl: 604800,
        disableTouch: true
    }),
    secret: "your_secret_key_make_it_hard_as_hell",
    cookie: {
        domain: ".example.com",
        sameSite: 'strict',
        secure: true
    },
    saveUninitialized: false,
    resave: false
}));

Upvotes: 2

Related Questions