How to develop secure .NET applications using Server SSL Certificates and Client Certificates – PART 4
The following article is part 4 and therefore the last in a 4 part series of articles about developing .NET applications using SSL. Part 1 in this series can be found here, part 2 can be found here and part 3 can be found here.
How to set up a web application to automatically redirect to HTTPS if accessed via HTTP when SSL is required
SSL can be “required” at the site level, folder level or even file level.
If any file that has SSL set to “required” is requested via HTTP, HTTP Error 403;4 “Forbidden” will be returned automatically by IIS. As far as I can tell, there is no simply way to tell IIS to re-direct to the same page via HTTPS. This effect can be achieved in two different ways and if “defence in depth” is the preferred approach then both solutions can be implemented together. Note that both solutions require custom code to be written however.
Redirect with IIS and code:
- Create a new Web Form (aspx) in your Web Application called RedirectToSSL (or similar).
- In the Page_Load event handler, insert the following code:
1 2 3 4 5 6 7 8
string redirectUrl = HttpContext.Current.Request.Url.Query; redirectUrl = redirectUrl.Substring((redirectUrl.LastIndexOf(';')+1) , redirectUrl.Length - (redirectUrl.LastIndexOf(';')+1)); System.UriBuilder secureUrlBuilder = new System.UriBuilder(redirectUrl); secureUrlBuilder.Scheme = System.Uri.UriSchemeHttps; secureUrlBuilder.Port = -1; // Use default port HttpContext.Current.Response.Redirect(secureUrlBuilder.Uri.ToString(), true);
- The aspx needs to be at least 512 bytes, otherwise IIS won’t redirect to it. So make sure you don’t delete everything out of it, it should never get displayed anyway.
- In IIS, right-click your Web Site and go to Properties > Custom Errors.
- Select the “403;4” HTTP error in the list HTTP errors and click the Edit Properties button.
- Select “URL” from the Message type drop-down list and enter “/RedirectToSSL.aspx” into the URL textbox, as shown below.
- Press OK twice to close the dialogs down.
- Restart the website and/or reset IIS to ensure all settings have been applied.
- Open Internet Explorer and go to:
https://<servername>/<securedpage>and verify that you are automatically redirected to the https version of the same page.
Redirect with code alone:
- Insert the following code at the beginning of the Page_Load event handler of every page that needs to be secured:
1 2 3 4 5 6 7 8 9
// Make sure the request has come through SSL (ie that HTTPS has been used) if (!HttpContext.Current.Request.IsSecureConnection) { System.Uri currentUrl = HttpContext.Current.Request.Url; System.UriBuilder secureUrlBuilder = new System.UriBuilder(currentUrl); secureUrlBuilder.Scheme = System.Uri.UriSchemeHttps; secureUrlBuilder.Port = -1; HttpContext.Current.Response.Redirect(secureUrlBuilder.Uri.ToString(), true); }
