In ASP.NET Core, how do AuthorizationOptions.DefaultPolicy and FallbackPolicy differ, and what changes when the fallback requires an authenticated user?
answer
- declared without a name vs not declared
- DefaultPolicy: RequireAuthenticatedUser()
- FallbackPolicy: null out of the box
- SetFallbackPolicy / AddFallbackPolicy
- MapStaticAssets endpoints need AllowAnonymous
basics
~20 sDefaultPolicy applies where authorization is declared without a policy name, such as a bare [Authorize]; it requires an authenticated user. FallbackPolicy, null by default, applies where no authorization metadata exists. Setting it makes every undecorated endpoint require sign-in, so public ones need [AllowAnonymous].
solid answer
~40 s`DefaultPolicy` is what a bare `[Authorize]` or `.RequireAuthorization()` means; out of the box it is `RequireAuthenticatedUser()`. `FallbackPolicy` is used only when an endpoint has **no** authorization metadata at all, and it is `null` by default, which is why undecorated endpoints are public. Setting the fallback to require an authenticated user, with `AddAuthorizationBuilder().SetFallbackPolicy(...)`, makes the app **secure by default**: a forgotten attribute now fails closed. The cost is that everything public must opt out with `[AllowAnonymous]` or `.AllowAnonymous()`: login and registration, health checks, the OpenAPI document and, because `MapStaticAssets` serves files as endpoints, static assets too. Requests that match no endpoint are also covered, so an anonymous user gets a challenge instead of a 404. The two policies are never combined: an endpoint with `[Authorize(Policy = "X")]` uses only `X`.
code
csharp · 16 linesbuilder.Services.AddAuthorizationBuilder()
.SetFallbackPolicy(new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build())
.AddPolicy("ContractEditor", p => p.RequireRole("Legal", "Manager"));
var app = builder.Build();
app.MapStaticAssets()
.Add(e => e.Metadata.Add(new AllowAnonymousAttribute()));
app.MapHealthChecks("/healthz").AllowAnonymous();
app.MapPost("/account/login", Login).AllowAnonymous();
app.MapGet("/contracts", ListContracts); // fallback: signed-in user
app.MapPut("/contracts/{id:int}", EditContract)
.RequireAuthorization("ContractEditor"); // named policy onlygo deeper
Recall that a bare [Authorize] means signed in, and that endpoints without any attribute are public unless a fallback policy is set.
Explain which metadata triggers DefaultPolicy, which situation triggers FallbackPolicy, and that the two are never merged with a named policy.
Roll out a secure-by-default fallback safely: inventory public endpoints, opt out health checks, static assets and login, and expect unmatched URLs to challenge.
Argue for failing closed as an organisation-wide default, and decide how exceptions to it are reviewed so [AllowAnonymous] does not become the new forgotten attribute.
## Two policies for two situations The authorization middleware turns an endpoint's metadata into one `AuthorizationPolicy`. Two properties on `AuthorizationOptions` fill the gaps: | Property | Used when | Out-of-the-box value | |---|---|---| | `DefaultPolicy` | Authorization is **declared** but names no policy or roles: `[Authorize]`, `[Authorize(AuthenticationSchemes = ...)]`, `.RequireAuthorization()` | `RequireAuthenticatedUser()` | | `FallbackPolicy` | **No** authorization metadata produced a policy | `null`, meaning no authorization is required | The source comment on `FallbackPolicy` puts it plainly: it is used "when no authorization metadata (e.g., `[Authorize]` attribute, `RequireAuthorization()`) is explicitly provided". The two are **never combined**. An endpoint with `[Authorize(Policy = "ContractEditor")]` is evaluated against `ContractEditor` alone, whatever the fallback says. ## Changing the default policy Replacing `DefaultPolicy` changes the meaning of **every** bare `[Authorize]` in the app. That is useful when all protected endpoints should, for example, accept only the JWT scheme or require an `employee` claim. It is risky as a quick fix, because a reader seeing `[Authorize]` assumes "signed in" and nothing more. `AuthorizationBuilder` offers `SetDefaultPolicy(policy)`, and `AddDefaultPolicy(name, ...)`, which also registers the policy under a name. ## Secure by default with a fallback The common use of the fallback is to invert the app's default: - Before: an endpoint is public unless someone remembers `[Authorize]`. - After `SetFallbackPolicy(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build())`: an endpoint needs a signed-in user unless someone deliberately writes `[AllowAnonymous]`. A missing attribute now fails **closed**: a new endpoint added in a hurry is protected, and the mistake shows up as a 401 in testing instead of a data leak in production. In a contract-management system, where nearly every endpoint touches contracts, this is usually the right default. ## What the fallback also catches The fallback applies to every request the authorization middleware processes without a policy from metadata, which includes more than controller actions: 1. **Public endpoints you own**: login, registration and password reset; `MapHealthChecks("/healthz")`, which a load balancer probes without credentials; `MapOpenApi()` if the document should stay public. Each needs `.AllowAnonymous()`. 2. **Static assets mapped as endpoints.** Since ASP.NET Core 9, `MapStaticAssets()` serves `wwwroot` files through endpoints, so the fallback protects them, and the sign-in page's own CSS would need a sign-in. Opt out by adding `AllowAnonymousAttribute` to that builder's endpoint metadata. Files served by `UseStaticFiles()` **before** the authorization middleware never reach it and stay public. 3. **Requests that match no endpoint.** The middleware still runs, finds no metadata, and applies the fallback. An anonymous request for a URL that does not exist therefore gets a challenge (401 or a login redirect) rather than a 404. ## How the middleware picks, step by step For each request the middleware reads the selected endpoint's metadata and decides: 1. Any `[Authorize]` or `RequireAuthorization(...)` data present? Named policies and roles are resolved; bare declarations add `DefaultPolicy` unless an explicit `AuthorizationPolicy` instance is also attached. 2. Any `AuthorizationPolicy` instances present? They are combined in. 3. Still no policy? Ask for `FallbackPolicy`; if it is `null`, call the next middleware without any check. 4. `[AllowAnonymous]` present? Authenticate to populate `User`, then continue without enforcing the result. 5. Otherwise evaluate the policy and challenge or forbid on failure. Step 3 is the only place the fallback is consulted, which is why it can never weaken or strengthen a declared policy. ## Which tool for which goal - "Every protected endpoint should accept only our JWT scheme": change `DefaultPolicy`. - "Nothing should be public by accident": set `FallbackPolicy`. - "These endpoints need a special rule": a named policy through `AddPolicy`, which neither of the other two affects. ## Traps when introducing it late - Turning the fallback on in a mature app breaks every unannotated public endpoint at once; list them from the endpoint data source or the OpenAPI document first. - `[AllowAnonymous]` still lets authentication run, so a public endpoint can personalise content for signed-in users. - Tests that call public endpoints anonymously are the cheapest way to prove the opt-outs are complete.
- After enabling a fallback policy, anonymous users requesting a mistyped URL get a login redirect instead of a 404. Why?The authorization middleware still runs for requests that match no endpoint. With no metadata it applies the fallback, the anonymous user fails it and is challenged, which the cookie scheme renders as a login redirect. Signed-in users pass the fallback and then receive the 404.
- Does an endpoint with [Authorize(Roles = "Manager")] also get the fallback policy's requirements?No. Any authorization metadata that produces a policy replaces the fallback entirely; the fallback is never merged into a declared policy. Here the role requirement alone is evaluated, and an anonymous user fails it anyway because `IsInRole` is false.
- A bare [Authorize] uses the FallbackPolicy.
- FallbackPolicy requires an authenticated user out of the box.
- The fallback policy is added on top of every named policy.
- Setting a fallback has no effect on static files served by MapStaticAssets.
- Changing DefaultPolicy affects endpoints that have no [Authorize] at all.
Assumes ASP.NET Core 10; since 9, MapStaticAssets serves static files as endpoints, which the fallback policy then covers.