Search code examples
asp.net-identityasp.net-core-2.1

How to get max value of claims value in ASP.NET Identity?


In my case the user may be in multiple roles, for example user may be Admin and SysAdmin.

In admin role he has a claim ("Employee.Add", "Allow"), and in SysAdmin role a claim ("Employee.Add", "Deny"). In my case this user must be authorized when try to add an employee.

How to get this using a policy?


Solution

  • According to your description, I suggest you could try to use asp.net core Policy's RequireAssertion method to achieve your requirement.

    More details, you could refer to below codes:

            services.AddAuthorization(options => {
                options.AddPolicy("TestAccess", policy => policy.RequireAssertion(context =>
                {
                   // you could modify below codes due to your requirement
                   var re= context.User.Claims.Where(x => x.Type == "Employee.Add").First();
                    if (re != null)
                    {
                        if (re.Value == "Allow")
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
    
                    }
                    else
                    {
                        return false;
                    }
                }));
            });
    

    Then in the controller, you could use below codes:

    [Authorize(Policy = "TestAccess")]
    public class VacationController : Controller
    

    More details, you could refer to this article.