Back to Aspnetcore

ASP0025: Use AddAuthorizationBuilder to register authorization services and construct policies.

aspnetcore/diagnostics/asp0025.md

latest3.4 KB
Original Source

ASP0025: Use AddAuthorizationBuilder to register authorization services and construct policies.

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

Cause

The use of xref:Microsoft.Extensions.DependencyInjection.PolicyServiceCollectionExtensions.AddAuthorization%2A can be converted to the new xref:Microsoft.Extensions.DependencyInjection.PolicyServiceCollectionExtensions.AddAuthorizationBuilder%2A.

Rule description

Use AddAuthorizationBuilder to register authorization services and construct policies.

How to fix violations

To fix a violation of this rule, replace the usage of AddAuthorization with AddAuthorizationBuilder.

The code fix converts any usage of the setters for the following properties of xref:Microsoft.AspNetCore.Authorization.AuthorizationOptions:

These setter usages are converted to equivalent method calls on xref:Microsoft.AspNetCore.Authorization.AuthorizationBuilder:

No diagnostic is reported when the configure action passed to AddAuthorization uses any of the following members of AuthorizationOptions:

AuthorizationBuilder doesn't have equivalents for these members of AuthorizationOptions, so they can't be converted.

No diagnostic is reported if the configure action passed to AddAuthorization contains operations unrelated to AuthorizationOptions. The code fix would not be able to automatically map unrelated operations to the fluent API of AddAuthorizationBuilder.

The following example shows code that triggers this diagnostic:

csharp
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AtLeast21", policy =>
        policy.Requirements.Add(new MinimumAgeRequirement(21)));
});

var app = builder.Build();

app.UseAuthorization();

app.Run();

The following example shows the result of applying the code fix:

csharp
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthorizationBuilder()
  .AddPolicy("AtLeast21", policy =>
  {
        policy.Requirements.Add(new MinimumAgeRequirement(21));
  });

var app = builder.Build();

app.UseAuthorization();

app.Run();

When to suppress warnings

The severity level of this diagnostic is Information. Suppress warnings if you don't want to use the new syntax.