HTTPS in ASP.Net MVC – RequireHttp or is there a better way?

A common solution to implementing HTTPS in ASP.Net MVC is to decorate your controllers or action methods with the RequireHttp attribute. This is fine if you are happy with a redirect to HTTPS if a user types HTTP, however, this does open you to some attack vectors described here:

http://www.troyhunt.com/2011/11/owasp-top-10-for-net-developers-part-9.html

The drawback of not automatically redirecting is that the user must explicitly type HTTPS into the address bar. Since I’m designing an API for consumption by other developers and a user should NEVER be typing the address into the browser directly I don’t have to worry about that usability issue.

Instead, I used a controller base class I already had implemented with an OnActionExecuting override and added just two lines of code:

if(!filterContext.HttpContext.Request.IsSecureConnection) {
    filterContext.Result = new ViewResult(){ViewName="SSLError"};
}

I have a stripped down view in the Shared folder that displays a very simple error message something like “This site can only be accessed via HTTPS”. That’s it. No redirect for Dr Evil to take advantage off, some HTML is returned in the response.

If you don’t want to use a controller base class you can also implement this code in a custom ActionFilter attribute.