Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add multiple policies in action using Authorize attribute using identity 2.0?

I am identity 2.1.2 with asp.net core 2.0, I have application claim table which have claim type and claim value i.e Assets ,Assets Edit,Assets, Assets View, where claim types are same with distinct claim values and I am creating policies using claim type name which is working fine for me no clue about how to add multiple policies in one action. Below code is being used in startup file to create policies.

services.AddAuthorization(options =>
{
   var dbContext = SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder<MyDBContext>(),
      Configuration.GetConnectionString("TestIdentityClaimAuth")).Options;

   var dbCon = new MyDBContext(dbContext);
   //Getting the list of application claims.
   var applicationClaims = dbCon.ApplicationClaims.ToList();
   var strClaimValues = string.Empty;
   List<ClaimVM> lstClaimTypeVM = new List<ClaimVM>();
   IEnumerable<string> lstClaimValueVM = null;// new IEnumerable<string>();

   lstClaimTypeVM = (from dbAppClaim
         in dbCon.ApplicationClaims
      select new ClaimVM
      {
         ClaimType = dbAppClaim.ClaimType
      }).Distinct().ToList();

   foreach (ClaimVM objClaimType in lstClaimTypeVM)
   {
      lstClaimValueVM = (from dbClaimValues in dbCon.ApplicationClaims
         where dbClaimValues.ClaimType == objClaimType.ClaimType
         select dbClaimValues.ClaimValue).ToList();

      options.AddPolicy(objClaimType.ClaimType, policy => policy.RequireClaim(objClaimType.ClaimType, lstClaimValueVM));
      lstClaimValueVM = null;
   }
});

And in my controller using the Autherize attribute like this.

[Authorize(Policy = "Assets Edit")]

Please shade some light on it thanks in advance.

like image 834
Alok Binwal Avatar asked Oct 03 '18 13:10

Alok Binwal


People also ask

How do I add an authorization policy?

Authorization Policy The user must satisfy all the requirements. We Add the policy using the AddAuthorization method in the ConfigureServices of the startup class. options. AddPolicy("AdminOnly", policy => policy.

How would you apply an authorization policy to a controller in an ASP.NET Core application?

Role-Based Authorization in ASP.NET Core You can specify what roles are authorized to access a specific resource by using the [Authorize] attribute. You can even declare them in such a way that the authorization evaluates at the controller level, action level, or even at a global level. Let's take Slack as an example.

How does Authorize attribute work C#?

If a user is not authenticated, or doesn't have the required user name and role, then the Authorize attribute prevents access to the method and redirects the user to the login URL. When both Roles and Users are set, the effect is combined and only users with that name and in that role are authorized.

Where can the Authorize attribute can be applied?

You can place the Authorize attribute on a controller or on individual actions inside the controller. When we place the Authorize attribute on the controller itself, the authorize attribute applies to all of the actions inside.

What happens if an authorization policy contains multiple authorization requirements?

If an authorization policy contains multiple authorization requirements, all requirements must pass in order for the policy evaluation to succeed. In other words, multiple authorization requirements added to a single authorization policy are treated on an AND basis. A requirement doesn't need to have data or properties.

How do I create an authorization policy for a controller?

Use IAuthorizationService, [Authorize (Policy = "Something")], or RequireAuthorization ("Something") for authorization. For apps that use Razor Pages, see the Apply policies to Razor Pages section. Apply policies to controllers by using the [Authorize] attribute with the policy name. For example:

What is policy based authorization in ASP NET Core?

Policy-based authorization in ASP.NET Core. Underneath the covers, role-based authorization and claims-based authorization use a requirement, a requirement handler, and a pre-configured policy. These building blocks support the expression of authorization evaluations in code. The result is a richer, reusable, testable authorization structure.

What are the three elements of an authorization policy?

Authorization rules have three elements: name, attributes, and permissions. It is the permissions function that maps to an authorization profile. This chapter provides a description of authorization policies and provides example procedures for the following authorization policy-related tasks:


1 Answers

For multiple policys, you could implement your own AuthorizeAttribute.

  • MultiplePolicysAuthorizeAttribute

    public class MultiplePolicysAuthorizeAttribute : TypeFilterAttribute
    {
         public MultiplePolicysAuthorizeAttribute(string policys, bool isAnd = false) : base(typeof(MultiplePolicysAuthorizeFilter))
         {
             Arguments = new object[] { policys, isAnd };
         }
    }
    
  • MultiplePolicysAuthorizeFilter

    public class MultiplePolicysAuthorizeFilter : IAsyncAuthorizationFilter
    {
        private readonly IAuthorizationService _authorization;
        public string Policys { get; private set; }
        public bool IsAnd { get; private set; }
    
        public MultiplePolicysAuthorizeFilter(string policys, bool isAnd, IAuthorizationService authorization)
        {
           Policys = policys;
           IsAnd = isAnd;
           _authorization = authorization;
        }
    
        public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            var policys = Policys.Split(";").ToList();
            if (IsAnd)
            {
                foreach (var policy in policys)
                {
                    var authorized = await _authorization.AuthorizeAsync(context.HttpContext.User, policy);
                    if (!authorized.Succeeded)
                    {
                        context.Result = new ForbidResult();
                        return;
                    }
    
                }
             }
             else
             {
                foreach (var policy in policys)
                {
                     var authorized = await _authorization.AuthorizeAsync(context.HttpContext.User, policy);
                     if (authorized.Succeeded)
                     {
                         return;
                     }
    
                }
                context.Result = new ForbidResult();
                return;
            }
         }
    }
    
  • only require one of the policy

    [MultiplePolicysAuthorize("Assets View;Assets Edit;Assets Delete")]
    
  • only require all the policys

    [MultiplePolicysAuthorize("Assets View;Assets Edit;Assets Delete", true)]
    
like image 181
Edward Avatar answered Sep 19 '22 14:09

Edward