Thursday, January 14, 2010

Using SSL with ASP.NET MVC 2

In ASP.NET MVC 1 you had to create a custom Authorization Filter to enable SSL. In ASP.NET MVC 2 the work is done for you. Just apply the RequireHttps actionfilter on top of your controller and all calls to your action methods will use SSL.

The attribute checks if the request is secure, and if not redirect to a secure version of the request. It’s also a good idea to set the Order parameter to 1. This ensures that the check for the use of SSL is executed before the check for the role. This helps ensure that credentials are only sent over SSL.

   1:  public AccountController: Controller
   2:  {
   3:     [RequireHttps(Order=1), Authorize(Roles="Users",Order=2)]
   4:     public ActionResult Login()
   5:     {
   6:        // Add login logic
   7:        return View();
   8:     }
   9:  }


Mark said...

Have you figured out how to get out of secure if you have a site that has both secure and unseured pages?

For instance a shopping site with unsecured pages that has a cart with secured pages.

Ed said...

Just decorate the action methods you want ssl with the attribute, and the ones you don't want ssl leave off the attribute.

You can also create a base controller and implement it once on the base controller if your entire site is ssl.