Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: How to automatically disable [RequireHttps] on localhost?

I want my login page to be SSL only:

    [RequireHttps]     public ActionResult Login()     {         if (Helper.LoggedIn)         {             Response.Redirect("/account/stats");         }          return View();     } 

But obviously it doesn't work on localhost when I develop and debug my application. I don't wanna use IIS 7 with SSL certificates, how can I automatically disable the RequireHttps attribute?

Update

Based on info provided by StackOverflow users and ASP.NET MVC 2 source code I created the following class that solves the problem.

public class RequireSSLAttribute : FilterAttribute, IAuthorizationFilter {     public virtual void OnAuthorization(AuthorizationContext filterContext)     {         if (filterContext == null)         {             throw new ArgumentNullException("filterContext");         }          if (!filterContext.HttpContext.Request.IsSecureConnection)         {             HandleNonHttpsRequest(filterContext);         }     }      protected virtual void HandleNonHttpsRequest(AuthorizationContext filterContext)     {         if (filterContext.HttpContext.Request.Url.Host.Contains("localhost")) return;          if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))         {             throw new InvalidOperationException("The requested resource can only be accessed via SSL");         }          string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;         filterContext.Result = new RedirectResult(url);     } } 

And it's used like this:

[RequireSSL] public ActionResult Login() {     if (Helper.LoggedIn)     {         Response.Redirect("/account/stats");     }      return View(); } 
like image 836
Alex Avatar asked Sep 02 '10 14:09

Alex


2 Answers

The easiest thing would be to derive a new attribute from RequireHttps and override HandleNonHttpsRequest

protected override void HandleNonHttpsRequest(AuthorizationContext filterContext)         {             if (!filterContext.HttpContext.Request.Url.Host.Contains("localhost"))             {                 base.HandleNonHttpsRequest(filterContext);             }         } 

HandleNonHttpsRequest is the method that throws the exception, here all we're doing is not calling it if the host is localhost (and as Jeff says in his comment you could extend this to test environments or in fact any other exceptions you want).

like image 104
Chao Avatar answered Oct 08 '22 20:10

Chao


    public static void RegisterGlobalFilters(GlobalFilterCollection filters) {          if (!HttpContext.Current.IsDebuggingEnabled) {             filters.Add(new RequireHttpsAttribute());         }     } 
like image 42
anon Avatar answered Oct 08 '22 21:10

anon