Ray
Ray

Reputation: 1442

Testing for HTTP headers being returned from an ASP.NET MVC Application

I've added and removed a number of headers for security reasons, using two classic strategies in an MVC Application:

protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
    HttpContext.Current.Response.Headers.Remove("X-AspNet-Version");
    HttpContext.Current.Response.Headers.Remove("Server");
    HttpContext.Current.Response.Headers.Remove("X-AspNetMvc-Version");
}

And via the Web.Config:

<customHeaders>
    <remove name="X-Powered-By" />
    <add name="X-Frame-Options" value="DENY" />
</customHeaders>

Right now I am using NUnit paired with RhinoMocks for testing, FWIW.

Given the difficulties with mocking HttpContext, what would be a good way to ensure that custom headers are either present or not present in the http response for any of the views I return?

Upvotes: 3

Views: 456

Answers (1)

Old Fox
Old Fox

Reputation: 8725

The correct way to verify this behaviour is through an Component test. The reason is quite simple; You are trying to ensure a security issue, in UT nothing will ensure that your component will use this behaviour. I can offer you several options(code weaving tools, add public method and etc..) to test it as a UT however, IMO this is a classic case for Integration test.

To Component test this behaviour do the following steps:

Raise a self host server(Self-Host ASP.NET or OWIN to Self-Host ASP.NET)

Then in call a method and assert that the answer doesn't contains the headers:

HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url); 
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();  

Assert.IsFalse(myHttpWebResponse.Headers.ContainsKey("X-Frame-Options");
Assert.IsFalse(myHttpWebResponse.Headers.ContainsKey("Server");
Assert.IsFalse(myHttpWebResponse.Headers.ContainsKey("X-AspNetMvc-Version");
//todo: add logic which read the following parameters from the configuration
Assert.IsFalse(myHttpWebResponse.Headers.ContainsKey("X-AspNet-Version");
Assert.AreEquals("DENY", myHttpWebResponse.Headers["X-Frame-Options"]);

Upvotes: 5

Related Questions