Forcing SSL/HTTPS With ASP.NET MVC

Written by rsolberg on. Posted in All, Software Development, Technology

I have recently been working on a new internal application for my family’s insurance agency and I knew I wanted to force a secured connection. Being an insurance agency, there are various rules and regulations regarding data security that you can’t take for granted. We use SSL connections for all of our web applications and I needed to force this new application to use HTTPS.

If this were an ASP.NET site, you could do a couple of basic things depending on your implementation. For example, you could tap into the Application_BeginRequest event in the Global.asax file and check to see if HTTPS is being used and if not to simply redirect to the HTTPS version. Note, you could run into an issue if using this locally on your development machine and you could certainly add this to your if statement HttpContext.Current.Request.IsLocal.Equals(false) for a little perk. But, I’d recommend you use IIS Express with Visual Studio and setup your development environments to use SSL.

The other thing you could do with an ASP.NET site and even an ASP.NET MVC site is to setup some URL Rewrite rules within your web config. Please note that this process requires you to have proper versions of IIS and extensions installed on your web server. Adding the following code to the Web.Server area of your web config file would redirect HTTP traffic to HTTPS.

The IIS URL Rewrite feature may not work for everybody for various reasons, and there is a great code option in ASP.NET MVC that will allow you to force HTTPS traffic at a controller level. You could simply decorate your controller with [RequireHttps], but if your application has 20 controllers this is perhaps not an attractive option. What if you miss one? Instead what I’d recommend considering is developing your own controller base class to use in your application. This is a sample of what my base controller looks like.

You’ll see that not only do I have [RequireHttps] there, but I also have [AuthorizeUser]. I now have setup code that I want to run on every controller just one time that I can now use everywhere in my application. This is what my application controllers look like and notice that I didn’t have to tell it anything about HTTPS or how to authorize users as that was handled within the base controller.

It’s important to note that one of the properties for your web project is SSL Enabled and this will need to be set to true.

Be Sociable, Share!

Trackback from your site.

Leave a comment

© Copyright RSolberg, 2003 - 2014. All Rights Reserved