The following is a list of session management guidelines:
- No matter the authentication mechanism used, always implement session management and validate the session on every page and/or request.
- Use long, random, and unique session identifiers. Favor the mechanisms already implemented in major web development languages such as ASP.NET, PHP, and J2EE.
- Generate new session IDs for users on log in and log out. Permanently invalidate the used ones.
- Invalidate sessions and log users out after a reasonable time of inactivity—15 to 20 minutes. Provide a good balance between security and usability.
- Always give a user the explicit option to log out; that is, having a log out button/option.
- When using session cookies, make sure that all security flags are set:
- The Secure attribute is used to prevent the use of the session cookie over non-encrypted communication.
- The HttpOnly attribute is used to prevent access to the cookie value through scripting languages. This reduces the impact in Cross-Site Scripting (XSS) attacks.
- Use nonpersistent session cookies, without the Expires or Max-Age attributes.
- Restrict the Path attribute to the server's root (/) or the specific directory where the application is hosted.
- The SameSite attribute is currently only supported by Chrome and Opera web browsers. This provides extra protection against information leakage and Cross-Site Request Forgery (CSRF), by preventing the cookie from being sent to the server by external sites.
- Link the session ID with the user's role and privileges, and use it to verify authorization on every request.
More in-depth advice about this topic can be found in the Session Management Cheat Sheet of OWASP at https://www.owasp.org/index.php/Session_Management_Cheat_Sheet.