Search code examples
node.jsexpressauthenticationsessionoauth-2.0

What If Session Expires While User Is Still On The Website


Suppose that there are 5 minutes left for the session to expire when user enters the website.Every action that user will make after 5 minutes will be rejected by server if it requires you to login and naturally have a session. Isnt it a bad experience for users that they think they logged in 5 minutes ago but now the actions like liking,commenting,creating is rejected because you now have no session. Is there a way to solve this or do i have to just throw the user back into the login page again?

I use a session based auth system where user logs in and has a cookie in his browser related to the session.I am using express with node js so it would be awesome if you want to send a solution in code with node&express


Solution

  • If your timeout is this short, and you constantly need to obtain new tokens then you're probably best off having some frontend code that renews the token a little bit before the expiry.

    Another solution is to just send the request, intercept a 401 (if the token expired), then do the refresh and repeat the first action.

    If the 5 minutes was just as an example, but your session length is a lot more reasonable, then it may be good enough to ask the user to simply log in again and repeat the action.

    Which one is best for you is more of a product design question than a programming question so it's hard to objectively answer.

    At the risk of this sounding like a plug my oauth2 client will schedule an OAuth2 token refresh 1 minute before it expires if it knows the expiry time. If not, it will listen for a 401 and attempt to refresh and repeat the action.