1

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 :-)

2
  • What do you mean "dynamic role"? Commented Sep 6, 2017 at 20:15
  • Try to make a convention and use regular expression in the Authorize attribute. I did that in past I don't know if is supported right now. Commented Sep 6, 2017 at 20:49

2 Answers 2

1

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!

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.