In ASP.NET Core 10, a museum audio-guide API registers authentication, authorization and CORS but calls only app.UseCors(); why do rejected calls reach the browser as CORS errors instead of 401s?
answer
- WebApplication wraps your pipeline
- implicit UseRouting when endpoints exist
- auth added when its services are registered
- implicit auth runs before your middleware
- no implicit UseAntiforgery
basics
~20 sWebApplication adds UseAuthentication and UseAuthorization itself, right after its implicit UseRouting and ahead of everything in Program.cs. Authorization therefore rejects requests before UseCors runs, so the 401 carries no CORS headers. Call UseCors, UseAuthentication and UseAuthorization yourself, in that order.
solid answer
~40 sWhen `WebApplication` builds the real pipeline it wraps yours: the developer exception page in Development, then `UseRouting` if you mapped endpoints and did not call it, then `UseAuthentication` if `IAuthenticationSchemeProvider` is registered and `UseAuthorization` if `IAuthorizationHandlerProvider` is, unless you called them yourself; then your Program.cs middleware; then `UseEndpoints`. So in this API an expired token is rejected by the implicit authorization middleware before `UseCors` ever runs, and the 401 goes out without `Access-Control-Allow-Origin`; the browser hides it behind a CORS error and the client cannot refresh the token. The fix is explicit `app.UseCors(); app.UseAuthentication(); app.UseAuthorization();`. In 10.0.12 `WebApplication` still does not add `UseAntiforgery`, and a terminal `app.Run(handler)` in Program.cs runs before the implicit `UseEndpoints`.
code
csharp · 18 linesbuilder.Services.AddCors(o => o.AddPolicy("kiosk",
p => p.WithOrigins("https://kiosk.museum.example")));
builder.Services.AddAuthentication().AddJwtBearer();
builder.Services.AddAuthorization();
var app = builder.Build();
// Broken: WebApplication inserts UseAuthentication/UseAuthorization
// ahead of this line, so 401s are written before CORS runs.
// app.UseCors("kiosk");
// Fixed: take over the order explicitly
app.UseCors("kiosk");
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/tours/{id:int}", (int id) => Results.Ok(id)).RequireAuthorization();
app.Run();go deeper
Know that WebApplication adds routing and endpoint middleware for you when you map endpoints.
List the middleware WebApplication inserts, the conditions for each, and where your Program.cs code lands between them.
Diagnose symptoms such as 401s turning into CORS errors, endpoints never running behind a terminal Run, or antiforgery exceptions, and fix them by taking over the order explicitly.
Decide whether a team relies on the implicit pipeline or always spells out UseRouting and auth calls, trading brevity against an order every reviewer can see.
## What WebApplication builds around your code With the minimal hosting model, the `app` object in `Program.cs` collects **your** middleware into a source pipeline. When the host starts, `WebApplicationBuilder` builds the real (destination) pipeline and wires yours into the middle of it. The ASP.NET Core 10.0.12 source adds, in this order: 1. `UseDeveloperExceptionPage()` when the environment is Development. 2. `UseRouting()` if any endpoints are mapped and your code did not call `UseRouting` itself. 3. `UseAuthentication()` if `IAuthenticationSchemeProvider` is registered (which `AddAuthentication` does) and you did not call it. 4. `UseAuthorization()` if `IAuthorizationHandlerProvider` is registered (which `AddAuthorization` does) and you did not call it. 5. **Your** Program.cs middleware, in order. 6. `UseEndpoints()` at the end if any endpoints are mapped. The docs summarise this as "user configured middleware and endpoints are added between `UseRouting` and `UseEndpoints`". The consequence that bites is step 3 and 4: implicit authentication and authorization run **before anything you wrote**. ## Why the museum API shows CORS errors The audio-guide API's kiosk web app runs on another origin. Its Program.cs registers `AddCors`, `AddAuthentication().AddJwtBearer()` and `AddAuthorization()`, then calls only `app.UseCors("kiosk")` and maps `RequireAuthorization()` endpoints. The effective pipeline is: - implicit `UseRouting` - implicit `UseAuthentication` - implicit `UseAuthorization` - `UseCors("kiosk")` - implicit `UseEndpoints` A request with a valid token passes authorization, reaches `UseCors`, and the response gets its CORS headers. A request with an **expired** token is challenged by the authorization middleware, which writes a 401 and never calls `next`. `UseCors` never runs, so the 401 has no `Access-Control-Allow-Origin` header. The browser refuses to expose it to the script and logs a CORS failure, so the kiosk's "refresh token on 401" logic never fires. The fix the docs give is to take control of the order: ```csharp app.UseCors("kiosk"); app.UseAuthentication(); app.UseAuthorization(); ``` Calling `UseAuthentication` and `UseAuthorization` yourself sets a marker in the builder properties, and `WebApplication` then does not add its own copies. ## Other consequences of the implicit pipeline | Situation | Effect | |---|---| | no `UseRouting` call | routing runs at the start of the pipeline, before all your middleware, including static files | | middleware that must run before routing | call `UseRouting()` explicitly and place that middleware above it | | terminal `app.Run(handler)` in Program.cs | it runs before the implicit `UseEndpoints`, so mapped endpoints never execute; call `UseRouting` and `UseEndpoints` explicitly and put the terminal middleware after them | | antiforgery services registered | **no** middleware is added; an endpoint that requires antiforgery validation (for example a Minimal API binding `[FromForm]`) throws `InvalidOperationException` until you call `UseAntiforgery()` after authentication and authorization | | `WebApplication.CreateEmptyBuilder` | the developer exception page is not added | ## Taking control explicitly `WebApplication` decides what to add by looking at markers in the builder's properties. `UseRouting`, `UseAuthentication` and `UseAuthorization` each record that they ran, so writing them yourself switches the implicit copy off. A fully explicit pipeline for the audio-guide API reads: ```csharp app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseCors("kiosk"); app.UseAuthentication(); app.UseAuthorization(); app.UseAntiforgery(); // throws at startup unless AddAntiforgery() was called app.MapGet("/tours/{id:int}", (int id) => Results.Ok(id)).RequireAuthorization(); ``` Now the order on the page is the order that runs, apart from `UseEndpoints`, which is still appended at the end. A team can make this explicit form its convention once a pipeline has more than a handful of calls, because a reviewer cannot see the implicit steps. ## Diagnosing it - Read the pipeline as the framework builds it, not as Program.cs lists it: the implicit steps go around your code. - A symptom that appears only for **rejected** requests (401 or 403 shown as CORS errors) points at CORS running after the implicit auth middleware. - An `InvalidOperationException` saying an endpoint "contains anti-forgery metadata, but a middleware was not found that supports anti-forgery" means `UseAntiforgery` is missing; the same family of messages exists for authorization and CORS metadata when those middleware are missing or placed before routing.
- Does WebApplication add UseAntiforgery when AddAntiforgery is registered?Not in ASP.NET Core 10.0.12, whatever the 8.0 release notes say. An endpoint carrying antiforgery metadata that requires validation, such as a Minimal API binding `[FromForm]`, makes the endpoint middleware throw an `InvalidOperationException` until you call `app.UseAntiforgery()` after `UseAuthentication` and `UseAuthorization`.
- Why does a terminal app.Run(handler) at the end of Program.cs stop every mapped endpoint from running?Your Program.cs middleware sits between the implicit `UseRouting` and the implicit `UseEndpoints`. The terminal handler answers before the endpoint middleware is reached. Call `UseRouting()` and `UseEndpoints(_ => { })` yourself and place the terminal middleware after `UseEndpoints`.
- How do you make a middleware run before route matching in a WebApplication app?Call `app.UseRouting()` explicitly and register that middleware above it. Without the explicit call, routing is added at the start of the pipeline, ahead of all your middleware.
- WebApplication only adds middleware you call yourself; nothing is inserted implicitly.
- The implicit UseAuthentication runs after all middleware written in Program.cs.
- WebApplication adds UseAntiforgery automatically when antiforgery services are registered.
- Calling UseCors alone is enough; the framework moves authentication behind it.
- A terminal app.Run(handler) at the end of Program.cs runs after the endpoints.
Assumes ASP.NET Core 10.0.12: WebApplication adds the developer exception page, routing, authentication, authorization and endpoints, but not antiforgery, despite the 8.0 release notes saying it does.