coffee, black   no sugar


20070419 Thursday April 19, 2007
asp.net niceness

After my frustrating excursion into .Net's HTTP client stack I today had some positive experiences with ASP.NET which I'd like to share with you.

One of our projects had a security assessment and we did not protect our web application against XSRFs. XSRF POSTs to be exact.

Fair enough. So we considered what to do and my colleague came across a description of a nice ASP.NET feature, namely defined events during request processing which you can subscribe to. The real beef is that the subscriber gets handed the current HttpContext and can manipulate or completely take over the HTTP response.

So in a matter of minutes we could make sure that all POST requests against our web app had validation checks in place. And we did not touch a single page source for that. (Well to make sure that the POSTs were generated in a valid way was more work). My point is that the security policy could be added in an orthogonal way. So it will work for all future requests as well.

This is really neat.

So if you are really interested in this, I describe in more detail how it was done: You implement the interface System.Web.IHttpModule (which is trivial). In the Init() method, which is called at application startup, you can subscribe to application events. It looks like this:

public void Init(HttpApplication app) {
  this.app.PreRequestHandlerExecute += (new EventHandler(this.validate));
}
where validate is a private method in the same class and looks basically like this:
private void validate(Object source, EventArgs e) {
  HttpContext ctx = ((HttpApplication)source).Context;
  if ("POST".Equals(ctx.Request.RequestType)) {
    if (this_is_not_valid(ctx.Request)) {
      ctx.Response.StatusCode = 400;
      ctx.Response.End;
    }
  }
}
The last tiny thing you need to do is to announce to ASP.NET that your IHttpModule shall be used. You can add a section in your web.config about that:
<configuration>
  <system.web>
    <httpModules>
      <add name="Validation" type="org.eissing.myproject.Validation" />
    </httpModules>
  </system.web>
</configuration>
That's it, folks.

Technorati Tags: , ,