Tuesday, November 16, 2010

Enforcing HTTPS or HTTP in ASP.NET WebForm Pages

This is really simple and yet extremely effective... I add these two methods to my Page base class, and suddenly all of my WebForm pages redirect to https when the Request is not to localhost.

protected override void OnInit(EventArgs e)
{
  base.OnInit(e);
  PushSSL();
}

private void PushSSL()
{
  const string SECURE = "https://";
  const string UNSECURE = "http://";

  //Force required into secure channel
  if (!Request.IsLocal && !Request.IsSecureConnection)
    Response.Redirect(Request.Url.ToString().Replace(UNSECURE, SECURE));
}


This code is a simplified version of what I found in this post: 443 <--> 80 - Seamlessly moving requests in and out of SSL. His use of the System.Diagnostics.Conditional("SECURE") attribute on the PushSSL method is very interesting. I like it, but decided I didn't want the extra bit of build configuration complexity this round.

No comments: