Conditional https:// in ASP.Net MVC

ASP.Net MVC defines the RequireHttpsAttribute to require that a controller or an action is requested using the https protocol only.

Historically, there seems to have existed a RequireSslAttribute as well, but it does not live on MSDN any more.

I develop a web application which contains both public pages (i.e. http, browse without authentication) and administration pages which require a login, and, depending on customer policy, the login has to be performed using https.

So, depending on the installation (test/demo/production), login is required or not, and I want to make the requirement configurable.

The internetz make a couple of suggestions on this topic, such as SO answers on these questions: one, two, and a blog post.

So, let’s create an Authorization FilterAttribute based on this information:

  public class ConditionalHttpsAttribute : FilterAttribute, IAuthorizationFilter
  {
    public void OnAuthorization(AuthorizationContext filterContext)
    {
      var httpsCondition = [is https required for this installation?];

      if (!httpsCondition)
        return;

      var request = filterContext.HttpContext.Request;

      if (request.IsSecureConnection)
        return;

      if (request.IsLocal)             
        return;

      if (!String.Equals(request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) 
        return;

      string url = "https://" + request.Url.Host + request.RawUrl;
      filterContext.Result = new RedirectResult(url);
    }
  }

Add the [ConditionalHttps] attribute to any GET action that may require https, such as the Login form. All subsequent request will be in https as well (as long as you do not edit the URL in the browser).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.