skip to content

In ASP.NET Core, what do [Authorize] and [AllowAnonymous] do on controllers and actions, and how do Minimal API endpoints express the same rules?

level: juniorimportance: must knowfreq 80%

answer

  1. metadata the middleware reads
  2. bare attribute means DefaultPolicy
  3. Roles = "A,B" is either role
  4. controller and action attributes both apply
  5. RequireAuthorization() and AllowAnonymous()

basics

~20 s

[Authorize] marks an endpoint as needing authorization: bare, it applies DefaultPolicy (an authenticated user); Policy, Roles or AuthenticationSchemes narrow it. [AllowAnonymous] switches enforcement off. Minimal APIs chain RequireAuthorization() and AllowAnonymous(), or put the same attributes on the handler.

solid answer

~40 s

`[Authorize]` and `[AllowAnonymous]` are **endpoint metadata**; the authorization middleware reads them after routing has picked the endpoint. A bare `[Authorize]` uses `AuthorizationOptions.DefaultPolicy`, which out of the box only requires an authenticated user. `[Authorize(Policy = "ContractEditor")]` uses a named policy, `[Authorize(Roles = "Legal,Manager")]` requires **any one** of the listed roles, and `AuthenticationSchemes` picks which schemes build the user. On a controller the attribute covers every action; attributes on the controller and the action **all apply**. `[AllowAnonymous]` anywhere on the endpoint wins over every `[Authorize]`: authentication still runs, but a failure is not enforced. Minimal APIs say the same with `.RequireAuthorization()`, `.RequireAuthorization("ContractEditor")` and `.AllowAnonymous()`, or with the attributes placed on the handler lambda.

code

csharp · 16 lines
csharp
[ApiController]
[Route("api/contracts")]
[Authorize] // DefaultPolicy: any authenticated user
public class ContractsController : ControllerBase
{
    [HttpGet]
    public IActionResult List() => Ok();

    [HttpPut("{id:int}")]
    [Authorize(Policy = "ContractEditor")] // authenticated AND ContractEditor
    public IActionResult Edit(int id) => NoContent();

    [HttpGet("templates")]
    [AllowAnonymous] // wins over the controller's [Authorize]
    public IActionResult Templates() => Ok();
}

go deeper

for a junior

Know that [Authorize] needs a signed-in user by default, that [AllowAnonymous] opens an endpoint, and the Minimal API calls RequireAuthorization() and AllowAnonymous().

for a middle

Explain how attributes on controller and action combine, why one Roles string means any role, and that [AllowAnonymous] overrides every [Authorize] on the endpoint.

for a senior

Show you know these are metadata read by the middleware: an unknown policy fails at request time, authentication never rejects, and attributes cannot see a loaded resource.

for a principal

Talk about keeping authorization declarations reviewable across a large codebase, such as named policies over role strings and a fallback that makes forgetting an attribute safe.

## What the attributes actually are `[Authorize]` (`Microsoft.AspNetCore.Authorization.AuthorizeAttribute`) and `[AllowAnonymous]` (`AllowAnonymousAttribute`) do nothing by themselves. They are **metadata**: when routing builds an endpoint for an MVC action, a Razor Page or a Minimal API handler, the attributes found on it become part of `Endpoint.Metadata`. The **authorization middleware** (`UseAuthorization`, which `WebApplication` adds for you when authorization services are registered) then reads that metadata for the selected endpoint and turns it into one `AuthorizationPolicy`. Two consequences follow: - An endpoint with **no** authorization metadata is open, unless a `FallbackPolicy` has been configured (by default it is `null`). - **Authentication does not reject anything.** It only builds `HttpContext.User`. A request is refused only when the authorization middleware evaluates a policy and it fails. ## The forms of [Authorize] `AuthorizeAttribute` has three settable properties, and each changes the policy it produces: | Declaration | Policy that results | |---|---| | `[Authorize]` | `AuthorizationOptions.DefaultPolicy` — by default `RequireAuthenticatedUser()` | | `[Authorize(Policy = "ContractEditor")]` or `[Authorize("ContractEditor")]` | The named policy registered with `AddPolicy` | | `[Authorize(Roles = "Legal,Manager")]` | A role requirement satisfied by **any one** of the comma-separated roles; the default policy is not added | | `[Authorize(AuthenticationSchemes = "Bearer")]` | The default policy, evaluated against the user built by that scheme | A policy name that was never registered is not caught at startup. The middleware throws `InvalidOperationException` ("The AuthorizationPolicy named: 'X' was not found.") on the first request that reaches the endpoint, so a typo surfaces as a 500, not as a silently open endpoint. ## How several attributes combine `AuthorizeAttribute` allows multiple uses and is inherited, so an action often ends up with several. The rules are: 1. Every `[Authorize]` on the controller, its base classes and the action is **combined into one policy**, and **all** of its requirements must pass. `[Authorize(Roles = "Legal")]` on the controller plus `[Authorize(Roles = "Manager")]` on the action means the user needs both roles. 2. Inside **one** `Roles` string the roles are alternatives: `"Legal,Manager"` is either role. 3. `[AllowAnonymous]` anywhere on the endpoint — controller or action — **wins**. The middleware still authenticates with the policy's schemes so that `User` is populated, then calls the next middleware without enforcing the result. The third rule is the classic trap: putting `[AllowAnonymous]` on a controller and `[Authorize]` on one of its actions does **not** protect that action. ## The Minimal API equivalents Minimal API endpoints accept the same metadata through convention methods on the builder that `MapGet`, `MapPost` and friends return: - `.RequireAuthorization()` — same as a bare `[Authorize]`, so `DefaultPolicy` applies; - `.RequireAuthorization("ContractEditor")` — one or more named policies; - `.RequireAuthorization(p => p.RequireRole("Manager"))` — an inline policy; - `.AllowAnonymous()` — same as `[AllowAnonymous]`. The attributes also work directly on the handler: `app.MapGet("/contracts", [Authorize] () => ...)`. Both styles produce identical endpoint metadata, so the middleware cannot tell them apart. ## A contract-management example In a contract-management API, reading the contract list needs any signed-in user, editing needs the `ContractEditor` policy and the public status page is open: - `ContractsController` carries `[Authorize]`, so every action needs an authenticated user; - its `Edit` action adds `[Authorize(Policy = "ContractEditor")]`, so callers need an authenticated user **and** the policy; - `StatusController.Get` carries `[AllowAnonymous]`. The same rules on Minimal API endpoints would be `.RequireAuthorization()` on the list, `.RequireAuthorization("ContractEditor")` on the edit endpoint and `.AllowAnonymous()` on the status endpoint. ## Role strings versus named policies `[Authorize(Roles = "Legal,Manager")]` works, but it spreads the rule across every attribute that repeats it. When the rule changes, say a new `ContractAdmin` role should also edit, each attribute has to be found and edited, and one that is missed quietly disagrees with the rest. A **named policy** keeps the rule in one place: - register it once: `AddPolicy("ContractEditor", p => p.RequireRole("Legal", "Manager"))`; - reference it by name: `[Authorize(Policy = "ContractEditor")]` or `.RequireAuthorization("ContractEditor")`; - change the roles, claims or handlers behind it without touching a single endpoint. Role strings are fine for a small app or a one-off admin page; named policies are what reviewers expect once the same rule protects more than a couple of endpoints. ## What the attributes cannot do The attributes are evaluated **before** model binding and before the action runs, so a policy cannot see the contract the action is about to load. A rule such as "only the document's owner or a manager may edit it" needs an imperative call to `IAuthorizationService.AuthorizeAsync` with the loaded document, not a cleverer attribute.

  • A controller has [Authorize(Roles = "Legal")] and one of its actions has [Authorize(Roles = "Manager")]. Who can call that action?
    Only a user in **both** roles. Every `[Authorize]` on the controller and the action is combined into one policy and all its requirements must pass. To accept either role, put both names in one attribute: `[Authorize(Roles = "Legal,Manager")]`.
  • Does [AllowAnonymous] stop authentication from running for that endpoint?
    No. The authorization middleware still authenticates with the policy's schemes so that `HttpContext.User` is populated; it just skips enforcing a failure. An anonymous endpoint can therefore still greet a signed-in user by name.
  • What happens when [Authorize(Policy = "Editors")] names a policy nobody registered?
    Nothing at startup. On the first request to that endpoint the middleware asks the policy provider for it, gets `null` and throws `InvalidOperationException` with "The AuthorizationPolicy named: 'Editors' was not found.", so the caller sees a 500.

  • Putting [Authorize] on an action protects it even though the controller has [AllowAnonymous].
  • Roles = "Legal,Manager" requires the user to hold both roles.
  • Adding AddAuthentication alone makes every endpoint reject anonymous callers.
  • A bare [Authorize] uses the FallbackPolicy.
  • RequireAuthorization() on a Minimal API does something different from [Authorize] on a controller.