Bypass Authorize Attribute in .Net Core for Release Version

前端 未结 6 1962
梦如初夏
梦如初夏 2020-12-07 02:20

Is there a way to \"bypass\" authorization in asp.net core? I noticed that the Authorize attribute no longer has a AuthorizeCore method with which you could use to make dec

6条回答
  •  孤城傲影
    2020-12-07 02:35

    As pointed out in the comments, you can create a base class for all your requirement handlers.

    public abstract class RequirementHandlerBase : AuthorizationHandler where T : IAuthorizationRequirement
    {
        protected sealed override Task HandleRequirementAsync(AuthorizationHandlerContext context, T requirement)
        {
    #if DEBUG
            context.Succeed(requirement);
    
            return Task.FromResult(true);
    #else
            return HandleAsync(context, requirement);
    #endif
        }
    
        protected abstract Task HandleAsync(AuthorizationHandlerContext context, T requirement);
    }
    

    Then derive your requirement handlers from this base class.

    public class AgeRequirementHandler : RequirementHandlerBase
    {
        protected override HandleAsync(AuthorizationHandlerContext context, AgeRequirement requirement)
        {
            ... 
        }
    }
    
    public class AgeRequirement : IRequrement 
    {
        public int MinimumAge { get; set; }
    }
    

    And then just register it.

    services.AddAuthorization(options =>
    {
        options.AddPolicy("Over18",
                          policy => policy.Requirements.Add(new AgeRequirement { MinimumAge = 18 }));
    });
    

提交回复
热议问题