Click here to Skip to main content
11,641,064 members (67,252 online)
Click here to Skip to main content

Automatically Switch from HTTP to HTTPS

, 11 Oct 2006 CPOL 43K 388 27
Rate this:
Please Sign up or sign in to vote.
Implements a scenario where you want to enforce page-specific HTTP/HTTPS rendering.

Introduction

You may want to force certain pages in your website to only render under secure protocol. Likewise, to reduce server load, you may deny secure access to other pages.

Yahoo! Mail as an Example

If you browse to http://mail.yahoo.com/, you are redirected via HTTP 302 to https://login.yahoo.com/config/login_verify2?&.src=ym. Once you log in, you end up at a non-secure URL via script block re-direct: http://us.f348.mail.yahoo.com/ym/login?.rand=432ghtrtnrp1l.

Why the Two Different Methods of Redirect?

When an HTTP 302 is used to redirect from a non-secure URL (i.e., http: protocol) to a secure URL (i.e., https: protocol), Internet Explorer will only raise a dialog box if there is a problem with the certificate.

However, in the reverse situation (i.e., using HTTP 302 to redirect from a secure to a non-secure URL), Internet Explorer will always raise a warning dialog. This is bad. Luckily, it turns out that if you use a script block to do the same redirect, no warning is raised.

Implementation

First, we define a custom configuration class so we can place our URL base strings into web.config:

using System;
using System.Configuration;
namespace AA.switchprotocol
{
    public class SwitchProtocolSection : ConfigurationSection
    {
        [ConfigurationProperty("urls", IsRequired = true)]
        public UrlsFormElement Urls
        {
            get { return (UrlsFormElement)base["urls"]; }
        }
    }
    public class UrlsFormElement : ConfigurationElement
    {
        [ConfigurationProperty("baseUrl", IsRequired = true)]
        public string BaseUrl
        {
            get { return (string)base["baseUrl"]; }
        }
        [ConfigurationProperty("baseSecureUrl", IsRequired = true)]
        public string BaseSecureUrl
        {
            get { return (string)base["baseSecureUrl"]; }
        }
    }
}

Now we can define our base URL strings in the web.config:

<?xml version="1.0"?>
<configuration>
   <configSections>
      <section 
         name="SwitchProtocol"
         type="AA.switchprotocol.SwitchProtocolSection, __code"/>
   </configSections>
   <SwitchProtocol>
      <urls baseUrl="http://localhost" 
            baseSecureUrl="https://localhost" />
   </SwitchProtocol>
   <system.web>
      <compilation debug="false"/>
   </system.web>
</configuration>

Next, define a simple accessor to the configuration settings:

using System;
using System.Web.Configuration;
namespace AA.switchprotocol
{
   public static class Globals
   {
      public readonly static SwitchProtocolSection Settings =
         (SwitchProtocolSection)WebConfigurationManager.
            GetSection("SwitchProtocol");
   }
}

Implement a base page class with custom redirect logic:

using System;
namespace AA.switchprotocol.UI
{
   public class BasePage : System.Web.UI.Page
   {
      protected override void OnLoad(EventArgs e)
      {
         string scheme = Request.Url.Scheme;
         if (_issecure)
         {
            if (scheme != "https")
            {
               Response.Redirect(
                  Globals.Settings.Urls.BaseSecureUrl +
                  Request.RawUrl);
            }
         }
         else
         {
            if (scheme != "http")
            {
               string to = Globals.Settings.Urls.BaseUrl + 
                              Server.UrlEncode(Request.RawUrl);
               Server.Transfer("~/Tranz.aspx?to=" + to);
            }
         }
         base.OnLoad(e);
      }
      private bool _issecure = false;
      protected bool IsSecure {
         get { return _issecure; }
         set{ _issecure = value; }
      }
   }
}

Implement Tranz.aspx, which takes care of the script-block redirect:

<%@ Page Language="C#" Theme="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
   _to = Server.UrlDecode(Request.QueryString["to"]);
}
private string _to;
protected void js()
{
   Response.Write("window.location.replace(\"" + _to + "\");");
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<script type="text/javascript" language="JavaScript">
<!--
<% js(); %>
-->
</script>
<title></title></head><body></body>
</html>

Implement a base page, which defaults to secure:

using System;
namespace AA.switchprotocol.UI
{
   public class SecurePage : BasePage
   {
      protected override void OnLoad(EventArgs e)
      {
         IsSecure = true;
         base.OnLoad(e);
      }
   }
}

Conclusion

If you derive your page from BasePage, it will intercept secure requests and use a script block to redirect. If you derive from SecurePage, it will intercept non-secure requests and use an HTTP 302 redirect. This mimics the functionality of Yahoo! Mail, and works well for situations where you have a limited number of pages that must be secure and others which should never be secure.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

aanodide
Web Developer
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

 
QuestionA little question about the Tranz.aspx Pin
bembengarifin4-Mar-07 17:38
memberbembengarifin4-Mar-07 17:38 
Generalhere is a better solution Pin
cnoevil18-Oct-06 6:05
membercnoevil18-Oct-06 6:05 
GeneralRe: here is a better solution Pin
aanodide20-Oct-06 23:37
memberaanodide20-Oct-06 23:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150731.1 | Last Updated 11 Oct 2006
Article Copyright 2006 by aanodide
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid