Back to Aspnetcore

ASP0001: Authorization middleware is incorrectly configured

aspnetcore/diagnostics/asp0001.md

latest1.6 KB
Original Source

ASP0001: Authorization middleware is incorrectly configured

Value
Rule IDASP0001
CategoryUsage
Fix is breaking or non-breakingNon-breaking

Cause

An out of order call to xref:Microsoft.AspNetCore.Builder.AuthorizationAppBuilderExtensions.UseAuthorization%2A was detected in the application start up code.

Rule description

For authorization to be effective for endpoint routes, the call to UseAuthorization should appear between the calls to UseRouting and UseEndpoints. In the absence of this, the fallback policy, if configured, will be used to authorize all requests.

Consider the following code:

csharp
app.UseStaticFiles();
app.UseAuthorization();

app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.MapDefaultControllerRoute();
});

The call to UseAuthorization appears before UseRouting and consequently is not endpoint aware.

How to fix violations

Change the order in which the call to UseAuthorization and UseRouting are performed.

csharp
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapDefaultControllerRoute();
});

When to suppress warnings

It is safe to suppress this rule if the call to UseAuthorization is intended to authorize the fallback policy on all outgoing requests, or is meant to authorize resources not routed using endpoint routing.