Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 after [RequireHttps] how to ensure non https is used

I found This Post and it looks like what I was needing for an application, my question is how do you revert back to plain http when https is no longer needed? Will it inherently do this based on an action not having the [RequireHttps] annotation?

EDIT: I found a couple posts talking about moving from https to http (here & here). However, I'd still appreciate an answer to the question below.

Alternately, I had debated on having the application open in a new window. Is it a fair assumption that the https will only apply to the new window?

like image 810
Jared Avatar asked Jan 24 '12 19:01

Jared


2 Answers

ASP.NET MVC's RequireHttps only goes one way. In the past I have just created my own FilterAttribute implementation to allow travel both ways:

EnsureHttpsAttribute

  public class EnsureHttpsAttribute : FilterAttribute, IAuthorizationFilter
  {
    public void OnAuthorization(AuthorizationContext filterContext)
    {
      Verify.NotNull(filterContext, "filterContext");
      Verify.True(filterContext.HttpContext.Request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase), "filterContext");

      var request = filterContext.HttpContext.Request;
      if (request.Url != null && !request.IsSecureConnection && !request.IsLocal)
        filterContext.Result = new RedirectResult("https://" + request.Url.Host + request.RawUrl);
    }
  }

EnsureHttpAttribute

  public class EnsureHttpAttribute : FilterAttribute, IAuthorizationFilter
  {
    public void OnAuthorization(AuthorizationContext filterContext)
    {
      Verify.NotNull(filterContext, "filterContext");
      Verify.True(filterContext.HttpContext.Request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase), "filterContext");

      var request = filterContext.HttpContext.Request;
      if (request.Url != null && request.IsSecureConnection)
        filterContext.Result = new RedirectResult("http://" + request.Url.Host + request.RawUrl);
    }
  }

Almost the same implementation as RequireHttpsAttribute if memory serves; although the above implementation checks if it is a Local request and ignores the switch to HTTPS.

like image 118
Chris Baxter Avatar answered Nov 18 '22 09:11

Chris Baxter


I suggest you read this post:

http://www.codehosting.net/blog/BlogEngine/post/More-fiddling-with-MVC3-and-https.aspx

like image 41
Travis J Avatar answered Nov 18 '22 09:11

Travis J