How to mark Session Cookie Secure

In one of my previous posts I discussed why we need to mark the cookies as secured. It becomes quite essential to mark the forms authentication cookie and the session cookie as Secured because they contain user sensitive information. A quick solution to mark the ASP.Net session cookie (by default asp.net_sessionid) and the Forms authentication cookie (by default .ASPXAUTH) is to write the following code in your EndRequest Event handler. This code can be added in an HttpModule or in your global.asax file.

// this code will mark the forms authentication cookie and the
// session cookie as Secure.
if (Response.Cookies.Count > 0)
{
    foreach (string s in Response.Cookies.AllKeys)
    {
        if (s == FormsAuthentication.FormsCookieName || s.ToLower() == “asp.net_sessionid”)
        {
             Response.Cookies[s].Secure = true;
        }
    }
}

Forms Authentication cookie can also be marked secured by setting the requireSSL attribute in the tag in the web configuration file.

One key this to note is if the server has not been setup for SSL and this logic is used, a new session will be generated for each request. Be sure to use this code only when the HTTPS is used on web server.

This posting is provided “AS IS” with no warranties, and confers no rights.