views:

152

answers:

1

While looking into forms authorizing/authentication, I found that it is possible to do role based authorizing by adding an array of roles to a FormsAuthenticationTicket. That way I can write

User.IsInRole(role from database)

But is there any way to do the same thing with permissions on a role like :

if (User.IsInRole(role from database)) {
    if (User.CanRead()) {
        //--- Let the user read
    }
    if (User.CanWrite()) {
        //--- Let the user write
    }
}

I have read a couple of articles and forum post's where permission is added to the array instead of the roles, resulting in using

User.IsInRole(permission from database)

However that's not the same thing. Hope someone can give some input on this matter, throw a link to an article or better yet, an code sample.

+2  A: 

You're better off changing the way you think about a role. Use the term "permission" or "claim" if that helps. Then create all the roles you need and link a given user to all the necessary roles.

One user can belong to multiple roles. This way, the following simple code will work fine and you don't need to build your own unique way of how things work.

if(User.IsInRole(someRole) && User.IsInRole(someOtherRole))
{
  // do something
}

You can make some C# extension methods to make this more readable too:

if(User.IsInSomeRoleAndOtherRole())
{
   // do something
}

The extension methods can look something like the following. Create a new class with the following code, then include the class namespace in your code, and you can use the extension method as shown above.

using System.Security.Principal;

namespace MyCompany
{
  public static class MyExtensions
  {
    public static bool IsInSomeRoleAndOtherRole(this IPrincipal principal)
    {
      if (!principal.IsInRole("someRole"))
        return false;

      if (!principal.IsInRole("someOtherRole"))
        return false;

      return true; // the user meets the requirements
    }
  }
}
AndrewDotHay
+1 Yeah that's pretty cool.
griegs
Ok, I will do that. Can you show me how to make a extension method ?
Martin Overgaard
Thank you very much ;o)
Martin Overgaard