How do you apply a global authorization policy requiring authentication by default for every endpoint, with explicit opt-out for public ones?
Short answer
Setting options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build() makes authentication mandatory for every endpoint that doesn't have explicit [Authorize] or [AllowAnonymous] metadata, flipping the default from 'public unless marked otherwise'…
Advertisement
AModel answer
Setting options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build() makes authentication mandatory for every endpoint that doesn't have explicit [Authorize] or [AllowAnonymous] metadata, flipping the default from 'public unless marked otherwise' to 'protected unless explicitly marked public' -- a much safer default posture that prevents accidentally leaving a new endpoint unintentionally unauthenticated.
builder.Services.AddAuthorization(options => {
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
});
[AllowAnonymous] // must explicitly opt out for public endpoints
[HttpGet("health")]
public IActionResult Health() => Ok();Real-world example
A security audit recommends switching from the default 'opt-in to protection' model to a fallback policy requiring authentication everywhere by default, after discovering a newly added endpoint had been accidentally left completely unprotected for weeks.
Likely follow-ups
- What endpoints commonly need [AllowAnonymous] even with this fallback policy enabled?
- How does this interact with health check endpoints that orchestrators need to reach unauthenticated?
Related topics