Skipping SSL Connections Locally

When developing locally, often times you don’t want to use SSL for a variety of reasons.  There’s no real point, since the request isn’t going over the wire.  Most of the time, connections are done via the loopback 127.0.0.1 address (although localhost can be used) which throws certificate errors. 

This one problem is often easy to solve, but it relates to a bigger issue: dictating when (and when not) to use SSL on your site.  In the ol’ days, you wouldn’t want an entire site to be SSL for performance reasons.  Ideally, you want to gracefully redirect users to/from SSL based on the requirements of the page.  If a user navigates to a secure section like their account page, you’d like to use SSL.  If they navigate away to a page not needing SSL, you’d want to use http and not https. 

There are a LOT of ways to do this, such as using MVC filters for MVC based applications.  One way I’ve solved this before was simply calling a method like so with each request:

 private void SetupSslIfNeeded()
{           
    //bail out on local connections – never need ssl
    if (Request.IsLocal)
    {
        return;
    }

    bool requiresSsl = false;
    string curPath = Request.Path;

    if (curPath.StartsWith("/account", StringComparison.OrdinalIgnoreCase) ||
        curPath.StartsWith("/user", StringComparison.OrdinalIgnoreCase) ||
        curPath.StartsWith("/admin", StringComparison.OrdinalIgnoreCase))
    {
        requiresSsl = true;
    }

    //redirect to secure page
    if (requiresSsl && !Page.Request.IsSecureConnection)
    {
        string currentUrl = HttpContext.Current.Request.Url.ToString();
        string newUrl = currentUrl.Replace("https://", "https://");
        Response.Redirect(newUrl);
    }

    //redirect to non-secure page
    if (!requiresSsl && Page.Request.IsSecureConnection)
    {
        string currentUrl = HttpContext.Current.Request.Url.ToString();
        string newUrl = currentUrl.Replace("https://", "https://");

        Response.Redirect(newUrl);
    }
}

It’s a little more verbose than it needs to be, but it’s done to because there were a few port handling lines I left out for simplicity. 

What this will do is avoid using SSL for local connections, and any page on the site except for those in the account, user, or admin folders.   The main downside of this approach is that it requires a redirect, which is a round trip to the server.  Ideally, you’d want your links to always be smart enough to know if they should go https:// or https://, but realistically, context switching between SSL and non-SSL pages is pretty rare so the client needing to endure the few extra milliseconds is an acceptable situation.  This is the way we currently handle SSL on https://www.rockpaperazure.com