I came across a situation where a ASP.Net 1.1 application had a security scan done and one of the issues that came back was the fact that the cookies were not marked secure. Not a major issue. However, if you have a product base that is customized many times over, how do you change everything in production without wasting a lot of time and resources. The goal is to not modify the existing code for any of the product bases, create complete http cookie coverage, and simplify the testing and redeployment of a single assembly.
Interested in the fix?
Here is what I came up with....
An HttpModule. My HttpModule reads every cookie coming in and out, marks them as secure, sets and expiration time and forces it to http only. Basically, everything that needed to be done and more to the cookies in order to satisfy the security scans. Below is all the code we needed to create the http module.
using System;
using System.Web;
namespace Jaws.Core.Web
{
public class SecureCookies : IHttpModule
{
#region Implementation of IHttpModule
/// <summary>
/// Initializes a module and prepares it to handle requests.
/// </summary>
/// <param name="context">An <see cref="T:System.Web.HttpApplication" /> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application </param>
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += SecureAllCookies;
context.PreSendRequestContent += SecureAllCookies;
}
/// <summary>
/// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule" />.
/// </summary>
public void Dispose()
{
//Nothing to Dispose of at this point.
}
private static void SecureAllCookies(object sender, EventArgs e)
{
var context = (sender as HttpApplication);
if (context != null)
{
foreach (string cookie in context.Request.Cookies)
{
context.Request.Cookies[cookie].Secure = true;
context.Request.Cookies[cookie].Expires = DateTime.Now.AddMinutes(10);
context.Request.Cookies[cookie].HttpOnly = true;
}
}
}
#endregion
}
}
7da1fa02-8d82-41d2-9b71-f7ef0b711067|0|.0
.Net, Tips and Tricks