Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write AuthorizeAttribute if a role contains space

I am using MVC3/4. But it is just a general question in authorization.

One of the role I have is named "Trip Leader" in the database, which contains a space.

I tried [Authorize(Roles="'Trip Leader', Administrator")] but it failed to work. Can anyone help?

like image 562
Blaise Avatar asked Jun 08 '12 19:06

Blaise


1 Answers

Create your own attribute and derive from AuthorizeAttribute. Then override the AuthorizeCore method and implement your own logic with validation on a role that contains a space.

An example could be something like this:

    public class CustomAuthAttribute : AuthorizeAttribute
    {
       private readonly IUserRoleService _userRoleService;
       private string[] _allowedRoles;
    
       public CustomAuthAttribute(params string[] roles)
       {
          _userRoleService = new UserRoleService();
          _allowedRoles = roles;
       }
       protected override bool AuthorizeCore(HttpContextBase httpContext)
       {
        //something like this.
        var userName = httpContext.User.Identity.Name;
        var userRoles = _userRoleService .GetUserRoles(userName); // return list of strings
        return _allowedRoles.Any(x => userRoles.Contains(x));
       }
   }

Usage

[CustomAuth("role withspace","admin")]
public ActionResult Index()
{
}
like image 115
Rob Angelier Avatar answered Nov 08 '22 02:11

Rob Angelier