Noocyte’s Weblog

October 10, 2011

Howto use configurable rolenames to authorize attribute

Filed under: Work — Tags: , — noocyte @ 12:40

For one of my ASP.Net MVC 3 projects I make heavy use of the “[Authorize(Roles=…)]” syntax, but the fact that I have to type in the rolename there always rubbed me the wrong way. I started to experiment to see if I could perhaps use some code to get the rolename from configuration or something. By default I could not, but it was possible to inherit from the Authorize attribute and create my own to make this possible. And so that’s what I did, here is the code:

public class SecureAttribute : AuthorizeAttribute
{
     public SecureAttribute() : this(true)
     {
     }

     public SecureAttribute(bool requireAdmin) : base()
     {
          if (requireAdmin)
          {
               this.Roles = Configuration.AdminRoleName;
          }
     }
}

To use it:

[Secure]
public abstract class SecureController : Controller

Basically all I do is add two constructors to enable me to set the “Roles” property to whatever I have configured it to be. Now, this code is tailor to my specific project, so you wanna change stuff to match your requirements. Please also note that I use a “SecureController” that all my Controllers inherit from if they require Admin access. I did this to save exactly one line of code on all of my controllers! So instead of inheriting from just “Controller” and adding the “Secure” attribute they just inherit from “SecureController”, which has the attribute and inherits from “Controller”. Perhaps a bit over the top, but you never know; one day I might add some more stuff here.

If anyone can see anything wrong with this implementation, please let me know! I am fairly new to MVC and the ASP.Net Membership stuff… Smilefjes

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.