I blogged here about securing logon cookies in MVC3. After writing a custom attribute based on the [RequireHttps] attribute it turned out that the best way was to use the forms authentication properties in web.config instead.
But the custom attribute that I wrote ended up morphing into something that solves a different problem. When you use the [RequireHttps] attribute, you might notice that even when a user logs out they continue with an https connection on subsequent requests to your site. This is not a big problem, but I find it annoying since https is not needed anymore. A similar thing might happen if a user has accidentally bookmarked the https version of your site's homepage, in which case the encryption might be unnecessary.
So I changed my existing attribute class into the [LimitHttps] Attribute. It checks to see if you are using a secure connection AND are not authenticated, then switches you back to plain old http - unless you are visiting a route that requires https. This is how I'm using it:
1) add the [RequireHttps] attribute to Account\LogOn and Account\Register
2) set up forms authentication with requireSSL="true" in web.config
3) add this line to RegisterGlobalFilters() in Global.asax:
You'll now find that the following things happen:
- https will be enforced when a user is logged in
(this is due to the requireSSL property in web.config)
- if a user manually goes back to http, the login cookie will not be sent in the request
(also due to the requireSSL property)
- The LogOn and Register views in the Account controller will always use SSL (https)
(because we've added the [RequireHttps] attribute to them)
- when a user logs out, they will automatically revert back to http
(which is done by the [LimitHttps] attribute we've added)
- if a user visits the homepage with https they will switch back to http
(the [LimitHttps] attribute does this too)
The code can be downloaded by clicking below.