[Analyzer/Codefixer] Recommend using `AddAuthorizationBuilder` for configuring global policies
See original GitHub issueBackground 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
AddAuthorizationBuilderto 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.
Issue Analytics
- State:
- Created 10 months ago
- Comments:9 (9 by maintainers)

Top Related StackOverflow Question
Yes please and thank you! 🙏🏽
With regard to this, it seems like the general convention is to start with “Use …” so I’ve updated the description to mimick this.