MVC 5.0 [AllowAnonymous] and the new IAuthenticationFilter

后端 未结 3 1090
广开言路
广开言路 2021-01-04 01:53

When I create a new asp.net mvc 4.0 application, one of the first thing I do, is create and set a custom authorize global filter like so:

3条回答
  •  隐瞒了意图╮
    2021-01-04 02:25

    In answer to Question 1:

    The [AllowAnnoymous] attribute acts like a flag (it actually has no implementation logic within it). Its presence is merely checked for by the [Authorize] attribute during execution of OnAuthorization. Decompiling the [Authorize] attribute reveals the logic:

            bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true)
                                     || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true);
    
            if (skipAuthorization)
            {
                return;
            }
    

    [AllowAnnonymous] would never 'automagically' bypass the code in your custom attribute...

    So the answer to the second half of Question 1 is: Yes - if you want your custom attribute to react to the presence of the [AllowAnnonymous], then you would need to implement a check (similar to the above) for the [AllowAnnonymous] attribute in your custom [Authorize] attribute.

提交回复
热议问题