How to create a custom Authorize attribute for multiple policies in ASP.NET CORE

南楼画角 提交于 2019-12-25 00:45:26

问题


I want to authorize an action controller could access by multiple policies.

.e.g:

[Authorize([Policies.ManageAllCalculationPolicy,Policies.ManageAllPriceListPolicy]]
public async Task<IActionResult> Get(int id){}

Thank a lot.


回答1:


For multiple policys, you could implement your own AuthorizeAttribute.

  • AuthorizeMultiplePolicyAttribute

    public class AuthorizeMultiplePolicyAttribute:TypeFilterAttribute
    {
    public AuthorizeMultiplePolicyAttribute(string policies,bool IsAll):base(typeof(AuthorizeMultiplePolicyFilter))
    {
        Arguments = new object[] { policies,IsAll};
    }
    }
    
  • AuthorizeMultiplePolicyFilter

    public class AuthorizeMultiplePolicyFilter: IAsyncAuthorizationFilter
    {
    private readonly IAuthorizationService _authorization;
    public string _policies { get; private set; }
    public bool _isAll { get; set; }
    public AuthorizeMultiplePolicyFilter(string policies, bool IsAll,IAuthorizationService authorization)
    {
        _policies = policies;
        _authorization = authorization;
        _isAll = IsAll;
    }
    
    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
    
        var policys = _policies.Split(";").ToList();
        if (_isAll)
        {
            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;
        }
    }
    }
    
  • Add Policy you want on Startup

    services.AddAuthorization(options =>
        {
    
            options.AddPolicy("ManageAllCalculationPolicy", policy =>
                    policy.RequireAssertion(context =>
                        context.User.HasClaim(c => c.Type == "BadgeId")));
    
            options.AddPolicy("ManageAllPriceListPolicy", policy =>
                    policy.RequireAssertion(context =>
                        context.User.HasClaim(c => c.Type == "aaaa")));
        });
    
  • Authorization based on one of the policies

    [AuthorizeMultiplePolicy("ManageAllCalculationPolicy;ManageAllPriceListPolicy", false)]
    
  • Authorization based on all policies

    [AuthorizeMultiplePolicy("ManageAllCalculationPolicy;ManageAllPriceListPolicy", true)]
    



回答2:


No, you can not add multiple policies as an list with condition or. I think NetCore does not support.

Try to create a new policy.

services.AddAuthorization(options =>
{
    options.AddPolicy("BadgeEntry", policy =>
        policy.RequireAssertion(context =>
            context.User.HasClaim(c =>
                (c.Type == ClaimTypes.BadgeId ||
                 c.Type == ClaimTypes.TemporaryBadgeId) &&
                 c.Issuer == "https://microsoftsecurity")));
});

Reference: https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-2.1#why-would-i-want-multiple-handlers-for-a-requirement




回答3:


You can add multiple policies like that

services.AddAuthorization(options =>
{
    options.AddPolicy("BadgeEntry", PolicyClaimCheck.Any, new string[2] { "VT102","RS102" });
    options.AddPolicy("Notification", PolicyClaimCheck.All, new string[2] { "XTX101","NT102" });
});

If it is enough to have one, you should use PolicyClaimCheck.Any or If it must have all, you should use PolicyClaimCheck.All



来源:https://stackoverflow.com/questions/53627551/how-to-create-a-custom-authorize-attribute-for-multiple-policies-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!