Search code examples
asp.net.netasp.net-mvcauthorizationasp.net-identity

Search by name in ASP.NET Authorize Attribute


I am using ASP.NET Identity for Authorization, In the Role Table, I have roles like : 'Role 1','Role 2','Role 3','Role 4','Role 5','Role n'. It can be any numbers.

My requirement is that user having any of the role will be able to access the page.

[Authorize(Roles = "Role 1", "Role 2")] // In this example, Number of roles 
//are known. But in my case, number of roles is not known.
public ActionResult Index()
{
    return View();
}

Is there any way I can search for keyword "Role" only? Like SQL "%Role%" query.


Solution

  • AuthorizeAttribute does not have this feature, but you can derive a class from it and implement it yourself.

    You can use this code

    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        public string RolePattern { get; set; }
    
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (!base.AuthorizeCore(httpContext))
            {
                return false;
            }
    
            IPrincipal user = httpContext.User;
            if (!user.Identity.IsAuthenticated)
            {
                return false;
            }
    
            ClaimsIdentity claimsIdentity = (ClaimsIdentity)user.Identity;
            string[] roles = claimsIdentity.FindAll(claimsIdentity.RoleClaimType).Select(claim => claim.Value).ToArray();
    
            if (!string.IsNullOrEmpty(RolePattern) && !roles.Any(role => Regex.IsMatch(role, RolePattern)))
            {
                return false;
            }
    
            return true;
        }
    }
    

    And Add CustomAuthorize on your action

    [CustomAuthorize(RolePattern = "^[a-zA-Z0-9]*Role[a-zA-Z0-9]*$")] 
    public ActionResult Index()
    {
        return View();
    }