Wednesday, February 9, 2011

Switching between HTTP and HTTPS automatically in ASP.NET

I'm currently working an ASP.NET website and ran into a problem, which I think is pretty common. The problem is how to deal with secure pages. My first instinct is to add HttpContext.Current.Request.IsSecureConnection in the page load of every secured page, and then redirect back to the same page with "https" instead of "http" in the URL. The problem with this is if you don't have a SSL cert on your dev machine, the page will hang. The solution to this is simple: check if it's the dev environment and don't redirect to https.

This method does work, I am currently using it on a production website and there are no problems with it. I just put the logic in a user control, and put it on all the secured pages. However, as mentioned before, it requires an extra redirect.

And then I came across this elegant (open source!) solution to the project on Code Project:
Switching Between HTTP and HTTPS Automatically: Version 2 - CodeProject

In short, you add a reference to the WebPageSecurity.dll, and then in the web.config you specify which files and directories should be secured. It has an option just like "error page" where it only invokes on "RemoteOnly", so it won't try to redirect in your development environment.

I highly recommend using this solution, because it separates page security logic from the UI logic layer.

No comments:

Post a Comment

There was an error in this gadget