dotnet / aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
https://asp.net
MIT License
34.88k stars 9.85k forks source link

Analyzer to warn when [Authorize] is overridden by [AllowAnymous] from "farther" away #56310

Closed halter73 closed 4 days ago

halter73 commented 4 weeks ago

Background and Motivation

A lot of people don't realize that the relative order of [Authorize] and [AllowAnonymous] does not matter, and incorrectly assume that if they put [Authorize] "closer" to an MVC action than [AllowAnonymous], that it will still force authorization. The following code shows examples of where a closer [Authorize] attribute gets overridden by an [AllowAnonymous] attribute that is further away.

[AllowAnonymous]
public class OAuthControllerAnon : ControllerBase
{
}

[Authorize]
public class OAuthControllerAuthz : ControllerBase
{
}

[Authorize] // BUG
public class OAuthControllerInherited : OAuthControllerAnon
{
}

public class OAuthControllerInherited2 : OAuthControllerAnon
{
    [Authorize] // BUG
    public IActionResult Privacy() => null;
}

[AllowAnonymous]
[Authorize] // BUG
public class OAuthControllerMultiple : ControllerBase
{
}

[AllowAnonymous]
public class OAuthControllerInherited3 : ControllerBase
{
    [Authorize] // BUG
    public IActionResult Privacy() => null;
}

Proposed Analyzer

Title

[Authorize] overridden by [AllowAnonymous] from farther away

Message

This [Authorize] attribute is overridden by an [AllowAnonymous] attribute from farther away on '{0}'. See https://aka.ms/aspnetcore-warnings/ASP0026 for more details.

And then https://aka.ms/aspnetcore-warnings/ASP0026 would point to documentation explaining.

Category

Severity Level

Risks

This could have some false positives where [Authorize] and [AllowAnonymous] were intended to be used together like when specifying an authentication scheme (e.g. [Authorize(AuthenticationSchemes = “Cookies”)]). No analyzer can catch every accidental application of [AllowAnonymous], but false positives and negatives can be mitigated by making the analyzer more or less conservative as need be.

amcasey commented 3 weeks ago

Analyzer approved!

halter73 commented 4 days ago

The analyzer was added by #56244 and https://aka.ms/aspnetcore-warnings/ASP0026 now points to https://learn.microsoft.com/aspnet/core/diagnostics/ASP0026.