AllowAnonymous not working with Custom AuthorizationAttribute

后端 未结 8 605
一整个雨季
一整个雨季 2020-12-03 06:34

This has had me stumped for a while. None of the commonly encountered similar situations seem to apply here apparently. I\'ve probably missed something obvious but I can\'

相关标签:
8条回答
  • 2020-12-03 06:56
    public class MyAuthorizationAuthorize : AuthorizeAttribute, IAuthorizationFilter
    {
    public override void OnAuthorization(AuthorizationContext filterContext)
            {
                if (filterContext.HttpContext.Request.IsAuthenticated)
                {
                    bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ||
                        filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);
    
                    if (skipAuthorization) return;
    
                }
                else filterContext.Result = new HttpUnauthorizedResult();
            }
    }
    
    0 讨论(0)
  • 2020-12-03 07:00

    Using C#6.0 Create a static class that extends the ActionExecutingContext.

    public static class AuthorizationContextExtensions {
        public static bool SkipAuthorization(this ActionExecutingContext filterContext) {    
             Contract.Assert(filterContext != null);
             return filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Any()|| filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Any();
        }
    }
    

    Now your override filterContext will be able to call the extension method, just make sure they are in the same namespace, or include the proper using statement.

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class AuthorizeCustomAttribute : ActionFilterAttribute {
        public override void OnActionExecuting(ActionExecutingContext filterContext) {
            if (filterContext.SkipAuthorization()) return;// CALL EXTENSION METHOD
             /*NOW DO YOUR LOGIC FOR NON ANON ACCESS*/
        }
    }
    
    0 讨论(0)
提交回复
热议问题