ASP0026:
值 | |
---|---|
規則識別碼 | ASP0026 |
類別 | 使用方式 |
修正是中斷性還是非中斷性的 | 不間斷 |
原因
與 [Authorize]
屬性相比,將 [AllowAnonymous]
屬性放置在「更接近」MVC 動作的位置會覆寫 [AllowAnonymous]
屬性並強制授權,這似乎是直觀的。 不過,不一定是這種情況。 重要的是屬性的相對順序。
下列程式碼顯示了 [Authorize]
屬性被較遠的 [AllowAnonymous]
屬性覆寫的範例。
[AllowAnonymous]
public class MyController
{
[Authorize] // Overridden by the [AllowAnonymous] attribute on the class
public IActionResult Private() => null;
}
[AllowAnonymous]
public class MyControllerAnon : ControllerBase
{
}
[Authorize] // Overridden by the [AllowAnonymous] attribute on MyControllerAnon
public class MyControllerInherited : MyControllerAnon
{
}
public class MyControllerInherited2 : MyControllerAnon
{
[Authorize] // Overridden by the [AllowAnonymous] attribute on MyControllerAnon
public IActionResult Private() => null;
}
[AllowAnonymous]
[Authorize] // Overridden by the preceding [AllowAnonymous]
public class MyControllerMultiple : ControllerBase
{
}
規則描述
警告:[Authorize]
屬性被來自「更遠」的 [AllowAnonymous]
屬性覆寫。
如何修正違規
如果您看到此警告,則所要採取的正確動作取決於屬性背後的意圖。 如果不小心將端點公開給匿名使用者,則應該移除更遠的 [AllowAnonymous]
屬性。 如果 [AllowAnonymous]
屬性是要覆寫更接近的 [Authorize]
屬性,您可以在 [AllowAnonymous]
屬性之後重複 [Authorize]
屬性,以釐清意圖。
[AllowAnonymous]
public class MyController
{
// This produces no warning because the second, "closer" [AllowAnonymous]
// clarifies that [Authorize] is intentionally overridden.
// Specifying AuthenticationSchemes can still be useful
// for endpoints that allow but don't require authenticated users.
[Authorize(AuthenticationSchemes = "Cookies")]
[AllowAnonymous]
public IActionResult Privacy() => null;
}
隱藏警告的時機
此診斷的嚴重性層級為「資訊」。 如果您想要覆寫 [Authorize]
屬性,則可以隱藏警告。 不過,建議您在 [AllowAnonymous]
屬性後面重複 [Authorize]
屬性,讓意圖更為清楚。