Advertisement
Intermediate ASP.NET Core, Authorization

What is the purpose of the [AllowAnonymous] attribute, and how does it interact with a controller-level [Authorize] attribute?

Short answer

[AllowAnonymous] applied to a specific action overrides an [Authorize] attribute applied at the controller level, letting most of a controller's actions require authentication while specifically exempting individual actions (like a public health check or a login endpoint that…

Save ASP.NET Core mock interview
Advertisement
AModel answer
[AllowAnonymous] applied to a specific action overrides an [Authorize] attribute applied at the controller level, letting most of a controller's actions require authentication while specifically exempting individual actions (like a public health check or a login endpoint that logically lives in an otherwise-protected AccountController) -- action-level attributes always take precedence over controller-level ones for this purpose.
[Authorize]
public class AccountController : ControllerBase {
    [AllowAnonymous]
    [HttpPost("login")]
    public IActionResult Login(LoginDto dto) { ... }  // publicly accessible despite controller-level [Authorize]

    [HttpGet("profile")]
    public IActionResult Profile() { ... }  // requires authentication (inherits controller-level attribute)
}
Real-world example
An AccountController marked with a blanket [Authorize] attribute still allows anonymous access specifically to its Login and Register actions via [AllowAnonymous], since requiring authentication to log in would be a contradiction.
Likely follow-ups
  • Does [AllowAnonymous] interact with a global FallbackPolicy the same way it does with controller-level [Authorize]?
  • What happens with multiple [Authorize] attributes stacked on the same action?
Related topics