Overriding controller AuthorizeAttribute for just one action

前端 未结 4 1555
谎友^
谎友^ 2020-12-01 08:35

I have a controller decorated with an AuthorizeAttribute. The controller contains several actions that all require authentication apart from one action that requires some cu

4条回答
  •  时光说笑
    2020-12-01 09:18

    After way too much time, I came up with a solution. You need to decorate your controller with a custom AuthorizeAttribute.

    public class OverridableAuthorize : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var action = filterContext.ActionDescriptor;
            if(action.IsDefined(typeof(IgnoreAuthorization), true)) return;
    
            var controller = action.ControllerDescriptor;
            if(controller.IsDefined(typeof(IgnoreAuthorization), true)) return;
    
            base.OnAuthorization(filterContext);
        }
    }
    

    Which can be paired with AllowAnonymous on an Action

    [AllowAnonymous]
    

提交回复
热议问题