UsePathBase should insert before UseRouting() in WebApplicationBuilder.ConfigureApplication
- Dominant language
- C#
- Stars
- 38.4k
- Forks
- 10.9k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 281
Description
### Is there an existing issue for this?
- [x] I have searched the existing issues
### Is your feature request related to a problem? Please describe the problem.
I am trying use PathBaseMiddleware with WebApplicationBuilder and auth such as:
``` csharp
// ...
builder.Services.AddAuthorization();
builder.Services.AddAuthentication().AddCookie();
var app = builder.Build();
app.UsePathBase("/example");
// ...
app.MapControllers().RequireAuthorization();
```
when I access https://localhost:8080/example/api/weatherforecast, a exception page show:
> InvalidOperationException: Endpoint xxx contains authorization metadata, but a middleware was not found that supports authorization. Configure your application startup by adding app.UseAuthorization() in the application startup code. If there are calls to app.UseRouting() and app.UseEndpoints(...), the call to app.UseAuthorization() must go between them.
> Microsoft.AspNetCore.Routing.EndpointMiddleware.ThrowMissingAuthMiddlewareException(Endpoint endpoint)
Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
Microsoft.AspNetCore.Builder.Extensions.UsePathBaseMiddleware.InvokeCore(HttpContext context, PathString matchedPath, PathString remainingPath)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
This is becasue when I add UsePathBase(...), it will add a UseRoute after UsePathBase without Authorization.
WebApplication generate a middleware like this:
1. UseDeveloperExceptionPage
2. UseRouting
3. UseAuthentication
4. UseAuthorization
5. WireSourcePipeline
5.1 UsePathBase(...);
5.2 UseRouting(...)
5.3 other middleware user added.
6. UseEndpoints()
The final UseEndpoints(...) middleware will execute authz. The endpoint is matched on step 5.2。step 3 will not execute because no endpoint matched on step 2.
### Describe the solution you'd like
Add UsePathBase(...) to WebApplicationBuilder.ConfigureApplication(...) when environment ASPNET_PATHBASE set.
### Additional context
_No response_
Contributor guide
Assessment
This issue has not been assessed yet.