Tuesday, September 20, 2011

Force SSL in VB.NET

Today I'm wrapping up a project to convert an existing web site to use SSL communication only. This required adding HTTPS detection in various places to prevent mixed-content errors. I'm not entirely happy with my solution for that yet, so I'm not going to go into that right now.

What I do want to talk about is actually forcing the user over to HTTPS once your site is SSL-ready. The code I had used for many years on classic ASP sites was not working reliably; it would redirect, but to the home page instead of the page you tried to access.

ASP.NET has beefed up the Request object with some additional information we didn't have back in the old days (Request.IsSecureConnection and Request.Url). We also have a new way of including our function libraries, the App_Code folder.

  1. NameSpace myApplication
  2.     Public Class myLibrary
  3.         Public Shared Sub ForceSSL()
  4.             If Not System.Web.HttpContext.Current.Request.IsSecureConnection Then
  5.                 System.Web.HttpContext.Current.Response.Redirect(System.Web.HttpContext.Current.Request.Url.AbsoluteUri.Replace("http://", "https://"))
  6.             End If
  7.         End Sub
  8.     End Class
  9. End NameSpace

Then from each page on the site I import my custom library and run the subroutine:

  1. Imports myApplication.myLibrary
  2. Sub Page_Load(sender as Object, e as EventArgs)
  3.     ForceSSL()
  4.     'Rest of code goes here...
  5. End Sub

Supposedly there's a way to do this without code by modifying some settings in IIS, but I didn't have any success with that. The particular situation I'm dealing with has some fairly severe cohesion/coupling issues with certain pages being accessed from different subdomains.

Download the VB.NET source code for ForceSSL from Snipplr.com