Rasik Jain

Wednesday, December 06, 2006

Setting Secure Flag for Session Cookie in ASP.NET

A cookie can be set with the Secure flag, which makes it to be sent only over a secure channel, such as an SSL connections. This Secure flag will ensure that session cookies are sent only over secure channels to prevent them from being captured in transit.

If an application is using the default ASP.Net session ID (e.g. ASP.NET_SessionID) as the session token, the secure flag can be set using the following code.

Include the following statement in the Session_Start of the global.asax file:

protected void Session_Start(Object sender, EventArgs e)

{

// secure the ASP.NET Session ID only if using SSL

// if you don't check for the issecureconnection, it will not work.

if (Request.IsSecureConnection == true)

Response.Cookies ["ASP.NET_SessionID"].Secure = true;

}


If the .NET application is using a Forms Auth Cookie (e.g ASPXAUTH), then usually the secure flag is enabled through the web.config file within the tag using the requireSSL="true" property.

More Information Security Items at WebInfoSec Website

1 Comments:

  • Thanks, good job ! Useful.

    By Anonymous Anonymous, at 12:06 AM  

Post a Comment

<< Home