views:

70

answers:

3

ASP.NET MVC has good support for role-based security, but the usage of strings as role names is maddening, simply because they cannot be strongly-typed as enumerations.

For example, I have an "Admin" role in my app. The "Admin" string will now exist in the Authorize attribute of my action, in my master page (for hiding a tab), in my database (for defining the roles available to each user), and any other place in my code or view files where I need to perform special logic for admin or non-admin users.

Is there a better solution, short of writing my own authorization attribute and filter, that would perhaps deal with a collection of enumeration values?

+6  A: 

I usually use a class with a bunch of string constants. It's not a perfect solution, since you need to remember to stick to using it everywhere, but at least it gets rid of the possibility of typos.

static class Role {
    public const string Admin = "Admin";
}
Matti Virkkunen
I went with this solution due to it's simplicity. The code changes were minimal, since I only had to replace hard-coded strings with constant references.
MikeWyatt
+1  A: 

It's not that hard to customize AuthorizeAttribute in the way you suggest.

Subtype it, add a custom property for your enum type, and call ToString() on the passed value. Put that in the regular roles property. This should take just a few lines of code, and AuthorizeAttribute still does all the real work.

+1 for Matti, too, since consts are also a good choice.

Craig Stuntz
+1  A: 

I have used a static class defining a bunch of string constants as suggested by Matti and on my current project I use the below extension method with an enum. Both approaches work very well.

public static class EnumerationExtension
{
  public static string GetName(this Enum e)
  {
    return Enum.GetName(e.GetType(), e);
  }
}
ScottS