Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...