March 13th, 2008

ASP.NET MVC: Securing Your Controller Actions (The .NET Framework Way)

So I just read Rob Conery’s blog post on Securing Your Controller Actions in MVC. I was a little perplexed about why guys at Microsoft love to reinvent stuff they have already done. I know Rob Conery is a really smart guy and has a wonderful grasp of the .NET framework, so I would have to assume he knows about what I have outlined below. My only guess is that he just wanted to re-invent something that is already built in to the framework using his own code.

Basically what Rob did was the following, created two attributes for attaching on the MVC Controller Action:

RequiresAuthenticationAttribute

[RequiresAuthentication]public void Index () {
    RenderView("Index");
}

RequiresRoleAttribute

[RequiresRole(RoleToCheckFor = "Member")]public void Index () {
    RenderView("Index");
}

I have accomplished the same thing using an attribute that has been apart of .NET since 1.0. The attribute is called PrincipalPermissionAttribute and is part of the System.Security.Permission namespace. The best thing about it is that it is integrated in to the run time, so there is no chance of unwanted people getting through. It also accomplishes both of Robs attributes up above, plus more. Using the examples up above I will demonstrate how to use PrincipalPermissionAttribute to secure and protect your Controller Actions.

RequiresAuthenticationAttribute

[PrincipalPermission(SecurityAction.Demand, Authenticated = true)]public void Index () {
    RenderView("Index");
}

RequiresRoleAttribute

[PrincipalPermission(SecurityAction.Demand, Role = "Member")]public void Index () {
    RenderView("Index");
}

In addition if you were inclined you can restrict things to just one user name with PrincipalPermissionAttribute. So for instance if you wanted to restrict adding and removing roles and their permissions to only the username “SiteAdmin”, you would do the following.

[PrincipalPermission(SecurityAction.Demand, Name = "SiteAdmin")]public void RolesAdmin () {
    RenderView("RolesAdmin");
}

As you can see this is very powerful. Built in to the run time, by extending the CodeAccessSecurityAttribute, so it operates at a lower level than Rob’s solution. Only requires the use of one attribute, and throws only one exception called SecurityException.

I really hope that ASP.NET MVC doesn’t turn in to a lets-redo-everything-that-already-works framework, because they still have many issues that they need to achieve before ASP.NET MVC is usable, and focusing on things that are already implemented in the .NET framework doesn’t seem like the right course of action when developing a new offering.

Note: This post is not meant to poke fun or belittle all the wonderful work that the ASP.NET MVC team has accomplish. Just to point out something that is already part of the .NET framework that should be encouraged to be used.

Update (2008-3-15): Up above I wrote:

My only guess is that he just wanted to re-invent something that is already built in to the framework using his own code

I appologize Rob, I was in rant mode, and I got carried away.

Tags: , , , , , ,

Social: kick it on DotNetKicks.com | Bookmark | View blog reactions

This entry was posted on Thursday, March 13th, 2008 at 6:59 am and is filed under ASP.NET, C#, How To, Programming, Rant. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

12 Responses to “ASP.NET MVC: Securing Your Controller Actions (The .NET Framework Way)”

  1. DotNetKicks.com Says:

    ASP.NET MVC: Securing Your Controller Actions (My Way)

    You’ve been kicked (a good thing) - Trackback from DotNetKicks.com

  2. Lorenz Cuno Klopfenstein Says:

    Very nice.
    But in this case you can’t redirect the user to a default login page, if I’m not mistaken. How are unallowed accesses handled?

  3. Jesse Says:

    This post would make sense if the PrinicipalPermission actually did what Rob’s attributes accomplish. The PrinicpalPermission will always throw exceptions if the user isn’t authenticated or doesn’t have the required role. Rob’s attributes redirect an unauthenticated user to the login page. So if your goal is to throw always throw an exception then use the Principal Permission, otherwise if you want to go down the path of what asp.net does for unauthenticated users then follow the advice in Rob’s article. Nick, maybe you should fully understand what others are trying to accomplish before talking smack.

  4. ryan Says:

    So, with your method, is there a way to redirect the user to the login page, and subsequently to the page they were trying to reach after they login?

  5. Nick Berardi Says:

    It is clear that I need to provide a little more insight in to my solution and what I am doing to redirect the user to the login page. I have created an exception handling attribute that will turn specified exceptions in to specific response codes. In the case of SecurityException, it gets turned in to a “401 Unauthorized” response code.

    Source for ExceptionHandlerAttribute:
    http://code.google.com/p/coderjournal/source/browse/trunk/ManagedFusion.Web.Mvc/ExceptionHandlerAttribute.cs

    Also Rob’s solution had the nasty habit of assuming everybody was using Form Authentication, if I tried Passport, Windows, or Basic authentication I would be out of luck. That is why as demonstrated in the example below that set the status code to “401 Unauthorized” and then let whatever authentication module that I am using pick up on the status code and redirect me to a login page for Forms Authentication or pop open a Windows dialog for my credentials or take me off to a Microsoft Password authentication page.

    So I would do the following to my method to let the 401 float down to the EndResponse and then let the FormsAuthenticationModule or WindowsAuthenticationModule pick up the HTTP 401 Status Code and do what ever it does depending on what type of authentication you are using.

    [PrincipalPermission(SecurityAction.Demand, Name = "SiteAdmin")]
    [ExceptionHandler(401, "Unauthorized", typeof(SecurityException)]
    public void RolesAdmin () {
    RenderView(”RolesAdmin”);
    }

    Or I can redirect them to the correct action depending on the exception that is thrown

    [PrincipalPermission(SecurityAction.Demand, Name = "SiteAdmin")]
    [ExceptionHandler("Login", "User", typeof(SecurityException)]
    public void RolesAdmin () {
    RenderView(”RolesAdmin”);
    }

    Thanks,
    Nick

  6. Rob Conery Says:

    Nick I wrote a whole post on using PrinciplePermission but didn’t post it because I thought it was hitting a tack with a sledgehammer. You have to catch the Exception that is thrown (which some people do in Global.asax) or, like you did, come up with a secondary Filter. This isn’t a very good solution in my mind - more code for what payoff? They do the same thing - difference is that you can do more with a filter.

    Like redirects - even custom ones. You can also test to see if a user is logged in before tossing an Exception. If you noticed in my sample where I check a Role, I first see if the user’s logged in - if they aren’t redirect them while appending the proper Return. Your example above throws an Exception - which you’d have to code your way out of to handle properly.

    Finally - I’m not sure why you’d suggest the code is “Nasty” because it references FormsAuthentication. This is by way of example of course, so if you wanted to use a different Auth Scheme you could.

    >>>My only guess is that he just wanted to re-invent something that is already built in to the framework using his own code<<<

    That was unnecessary. I know you probably didn’t mean to insult, but that’s what it is.

  7. SubC Says:

    In ExceptionFilterAttribute, OnActionExecuted method used “filterContext.RedirectToAction” which is not supported in the March 2008 MVC release. How should the code be updated to reflect this?

    Thanks.

  8. Nick Berardi Says:

    Sorry about that I left the following two pieces of code out of SVN.

    http://code.google.com/p/coderjournal/source/browse/trunk/ManagedFusion.Web.Mvc/MvcExtensions.cs
    http://code.google.com/p/coderjournal/source/browse/trunk/ManagedFusion.Web.Mvc/WebExtensions.cs

  9. ASP.NET MVC Archived Buzz, Page 1 Says:

    [...] [FriendFeed] ASP.NET MVC: Securing Your Controller Actions (The .NET Framework Way) (7/13/2008)Sunday, July 13, 2008 from http://www.coderjournal.com [...]

  10. Matt Dwyer Says:

    “That was unnecessary. I know you probably didn’t mean to insult, but that’s what it is.”

    Pretty thin-skinned considering the troll jobs I’ve seen you do on other people. I hope some Hawaiian beats you senseless with your sunscreen bottle while you’re floundering in the shorebreak trying to get another action pic for your blog.

  11. Nick Berardi Says:

    Matt, Everything else left aside, I was in the wrong on this.

  12. Matt Dwyer Says:

    Obviously I have to respect your opinion on that, but I just don’t see it, consider your quote:

    >>>My only guess is that he just wanted to re-invent something that is already built in to the framework using his own code<<<

    Who hasn’t reinvented something in a/the framework with their own code at some point?

Leave a Reply