Martin Abrahams Team : Web Development Tags : Web Development

Securing content the MVC way

Martin Abrahams Team : Web Development Tags : Web Development

I've recently made the the switch from traditional ASP.net webforms to MVC. Besides the fact that it's a far better pattern to follow, I can now make use to a bunch of useful additions to the .net framework 4. 

Recently I was developing typical secure section on a new MVC4 website and instinctually went to follow the standard webforms approach of adding a custom section to my web.config. While this will work as expected, it's not ideal because it's completely seperated from the routing engine.

In MVC, to secure a single Action or an entire Controller you can simply add an [Authorize] attribute to the object, this will honour the authentication section in the web.config work just as we were used to with webforms.

To take it a step further you can also create a custom authorize attribute which inherits from AuthorizeAttribute. This came in handy for me to check a customer dependency every time a secure page was requested. I can put my custom logic in the override for AuthorizeCore in my custom attribute, this method is executed every time a requested secured page is requested. 

Previously to to the same thing in webforms this additional dependency logic would have to be tacked in somewhere such as the Global BeginRequest event with some reflection to determine if the requested page is defined as secure in the web.config and reject the user at that point. I've had to do this before and it's not the least bit elegant.