How to write AuthorizeAttribute if the role contains space

I am using MVC3 / 4. But this is just a general issue in authorization.

One of the roles that I have is called the Guidebook in the database, which contains a space.

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

+5
source share
2 answers

Create your own attribute and get from AuthorizeAttribute. Then override the AuthorizeCore method and implement your own logic, checking for a role that contains a space.

An example might 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));
   }

}

Using

[CustomAuth("role withspace","admin")]
public ActionResult Index()
{
}
+3
source

Try the following:

[Authorize(Roles="Trip Leader")]
[Authorize(Roles="Administrator")]

EDIT: . / , :

[Authorize(Roles="Trip Leader, Administrator")]
0

All Articles