Saturday, April 5, 2008

Force SSL

If your web site requires visitors to enter private information, like their credit card number, or even just a username and password, you're hopefully using SSL to secure the transmission. But providing SSL is not enough, because visitors can still access your site without SSL. When a visitor navigates to a page where they are entering private information, we want to enforce that their data is protected by SSL.

Our PHP programmer friends can do this via an htaccess file:

  1. RewriteEngine On
  2. RewriteCond %{HTTPS} off
  3. RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

But for those of us stuck using ASP, we don't have this luxury. We can achieve the same result with some code.

  1. sub forceSSL()
  2.     dim secureURL
  3.     if UCase(Request.ServerVariables("HTTPS")) = "OFF" then
  4.         secureURL = "https://" & Request.ServerVariables("SERVER_NAME") & Request.ServerVariables("HTTP_URL")
  5.         if Request.ServerVariables("QUERY_STRING") <> "" then
  6.             secureURL = secureURL & "?" & Request.ServerVariables("QUERY_STRING")
  7.         end if
  8.         Response.Redirect secureURL
  9.     end if
  10. end sub

There are some things here worth noting. In both the htaccess example and the ASP example, we are checking if HTTPS is off. Some people will instead check if traffic is coming from port 80, the standard HTTP port, or not coming from 443, the standard HTTPS port. Checking port numbers is not the best solution because the server administrator can set up HTTP and HTTPS to run on different ports. It's also worth noting that the above ASP example preserves QueryString variables, if any are being passed. Most other examples I've seen on the Internet ignore the QueryString variables, which leads to navigation problems.

With this subroutine in your arsenal, just call it at the top of any page you want to secure.

No comments: