dotnet / dotnet/aspnetcore

Consider updating AuthorizationMiddleware and CorsMiddleware to only set state in HttpContext if auth / cors metadata is present

Open
#38,342 6 comments 0 reactions 0 assignees View on GitHub
area-middleware area-networking Perf
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 5h
Merged PRs (30d)
276

Description

Endpoint routing only checks for state in HttpContext if the route has Auth or CORs metadata:

https://github.com/dotnet/aspnetcore/blob/main/src/Http/Routing/src/EndpointMiddleware.cs#L38-L48

However, the middlewares update HttpContext.Items any time it sees an endpoint:

* https://github.com/dotnet/aspnetcore/blob/main/src/Security/Authorization/Policy/src/AuthorizationMiddleware.cs#L51-L58
* https://github.com/dotnet/aspnetcore/blob/main/src/Middleware/CORS/src/Infrastructure/CorsMiddleware.cs#L126-L133

We might benefit from slight improvements for endpoints with Auth or CORS metadata by updating these middlewares to only update context when they know EndpointMiddleware is going to observe it i.e.

```C#
if (endpoint?..GetMetadata() is not null)
{
// EndpointRoutingMiddleware uses this flag to check if the CORS middleware processed CORS metadata on the endpoint.
// The CORS middleware can only make this claim if it observes an actual endpoint.
context.Items[CorsMiddlewareWithEndpointInvokedKey] = CorsMiddlewareWithEndpointInvokedValue;
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.