Skip to content

[Analyzer/Codefixer] Recommend using AddAuthorizationBuilder for configuring global policies #45219

@captainsafia

Description

@captainsafia

Background and Motivation

In .NET 7, we introduced an AddAuthorizationBuilder extension method on IServiceCollection that would register authorization-related services and provide an AuthorizationBuilder for constructing policies. This is an abbreviated syntax that allows reduces nesting in the original pattern of calling AddAuthorization and providing a policy construct as a callback.

Proposed Analyzer

Analyzer Behavior and Message

When the user provides code where AddAuthorizationBuilder would provide a more abbreviated style, recommend a codefix with the following message:

Use AddAuthorizationBuilder to register authorization services and construct policies.

Category

  • Design
  • Documentation
  • Globalization
  • Interoperability
  • Maintainability
  • Naming
  • Performance
  • Reliability
  • Security
  • Style
  • Usage

Severity Level

  • Error
  • Warning
  • Info
  • Hidden

Usage Scenarios

Before

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();

After

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();

Risks

Marking this as an info-only analyzer strikes a good balance between informing the user of this feature without being too presumptuous (via a warning). A refactoring would not have been good at educating the user about the functionality.

Metadata

Metadata

Assignees

Labels

analyzerIndicates an issue which is related to analyzer experiencearea-authIncludes: Authn, Authz, OAuth, OIDC, Bearerhelp wantedUp for grabs. We would accept a PR to help resolve this issue

Type

No type
No fields configured for issues without a type.

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions