Blog Post

IIS Support Blog
2 MIN READ

Session state and session cookies best practices

Nedim's avatar
Nedim
Icon for Microsoft rankMicrosoft
Jun 21, 2019

Best practices for the session state:

  • Change the default session ID name. In ASP.NET, the default name is ASP.NET_SessionId. This immediately gives away that the application is ASP.NET and that that cookie contains the session ID value
  • Make sure the length of the session ID is long enough to prevent brute force attacks. Recommended length is 128 bits
  • Make sure to create the session ID in a completely random way. This ensures that attackers can’t guess the session ID by using predictability analysis
  • Ensure that the session ID does not contain any additional sensitive data. The data should be a random string of characters with no meaning
  • HTTPS should be used for all session based applications handling sensitive data
  • Session cookies should be created with the Secure and HttpOnly attributes
  • Prevent concurrent sessions where possible
  • Destroy sessions upon timeout, logoff, browser close or log-in from a separate location

 

Best practices for the session cookies:

  • Do not store any critical information in cookies. For example, do not store a user’s password in a cookie. As a rule, do not keep anything in a cookie that can compromise your application. Instead, keep a reference in the cookie to a location on the server where the data is
  • Set expiration dates on cookies to the shortest practical time. Avoid using permanent cookies
  • Consider encrypting information in cookies
  • Consider setting the Secure and HttpOnly properties on the cookie to true

 

Example

Here are a few examples of implementing best practices for cookies:

 

Web.config file:

<system.web>
<sessionState regenerateExpiredSessionId="false" cookieless="UseCookies" cookieName="id" />
</system.web>

Code-behind file:

Response.Cookies.Add(new HttpCookie("id", ""));
Response.Cookies["id"].HttpOnly = true;
Response.Cookies["id"].Secure = Convert.ToBoolean(ConfigurationManager.AppSettings["SecureCookie"]);

 

References:

Updated Jun 21, 2019
Version 4.0
No CommentsBe the first to comment