Mohit Modi
Mohit Modi

Reputation: 61

how to use dynamic role in authorize attribute in asp.net mvc 5 identity

I am new in asp.net identity. I am trying to learn it. I want to understand about how to use dynamic role in authorize attribute in asp.net MVC 5 identity. because if we have lots of role in our application then we can not decorate it by hard-code. please help me by providing a good example in details.

Thank you in advance :-)

Upvotes: 1

Views: 2659

Answers (2)

Miguel
Miguel

Reputation: 3952

Extend the AuthorizeAttribute to support regex likes this:

class RegexAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null)
        {
           return base.AuthorizeCore(httpContext);
        }

        IPrincipal user = httpContext.User;
        if (user == null || user.Identity == null || !user.Identity.IsAuthenticated)
        {
            return base.AuthorizeCore(httpContext);
        }

        if (!string.IsNullOrEmpty(Users) && Regex.IsMatch(user.Identity.Name, Users))
        {
            return true;
        }

        if (!string.IsNullOrEmpty(Roles))
        {
            var rolesManager = new RoleStore<IdentityRole>(httpContext.GetOwinContext().Get<ApplicationDbContext>());
            var matchedRoles = rolesManager.Roles.Select(t => t.Name).AsEnumerable().Where(t => Regex.IsMatch(t, Roles));

            if (matchedRoles.Any(user.IsInRole))
            {
                return true;
            }
        }

        return base.AuthorizeCore(httpContext);
    }
}

Later you can organize your Roles in groups to be able to match a bunch of them using regular expressions like this:

    [RegexAuthorize(Roles = @"Role #\d")]
    public ActionResult About()
    {
        ViewBag.Message = "Your application description page.";

        return View();
    }

This will match all the following roles: Role #0, Role #1, ..., Role #9

Hope this help!

Upvotes: 1

moath naji
moath naji

Reputation: 661

you can find full explain and demo project supported by microsoft in this link with multiple examples on using mvc identity and roles , claims ....

MVC_Identity

Upvotes: 0

Related Questions