ASP.NET Core 中的簡單授權Simple authorization in ASP.NET Core

在 MVC 中的授權透過AuthorizeAttribute屬性以及其各種不同的參數。Authorization in MVC is controlled through the AuthorizeAttribute attribute and its various parameters. 簡單來說,套用AuthorizeAttribute控制器或動作限制存取的控制器或動作,任何已驗證的使用者屬性。At its simplest, applying the AuthorizeAttribute attribute to a controller or action limits access to the controller or action to any authenticated user.

例如,下列程式碼會限制存取AccountController,任何已驗證的使用者。For example, the following code limits access to the AccountController to any authenticated user.

[Authorize]
public class AccountController : Controller
{
    public ActionResult Login()
    {
    }

    public ActionResult Logout()
    {
    }
}

如果您想要將授權套用至動作,而不是控制器,套用AuthorizeAttribute屬性本身的動作:If you want to apply authorization to an action rather than the controller, apply the AuthorizeAttribute attribute to the action itself:

public class AccountController : Controller
{
   public ActionResult Login()
   {
   }

   [Authorize]
   public ActionResult Logout()
   {
   }
}

現在只有已驗證的使用者可以存取Logout函式。Now only authenticated users can access the Logout function.

您也可以使用AllowAnonymous允許未經驗證使用者個別動作時所存取的屬性。You can also use the AllowAnonymous attribute to allow access by non-authenticated users to individual actions. 例如: For example:

[Authorize]
public class AccountController : Controller
{
    [AllowAnonymous]
    public ActionResult Login()
    {
    }

    public ActionResult Logout()
    {
    }
}

這可讓只有經過驗證的使用者才能AccountController,除了Login供所有人不論其驗證或未驗證 / 匿名狀態的動作。This would allow only authenticated users to the AccountController, except for the Login action, which is accessible by everyone, regardless of their authenticated or unauthenticated / anonymous status.

警告

[AllowAnonymous] 會略過授權的所有陳述式。[AllowAnonymous] bypasses all authorization statements. 如果您合併[AllowAnonymous]以及任何[Authorize]屬性,[Authorize]屬性會被忽略。If you combine [AllowAnonymous] and any [Authorize] attribute, the [Authorize] attributes are ignored. 例如,如果您套用[AllowAnonymous]在控制器層級中,任何[Authorize]屬性相同的控制站上 (或其內的任何動作) 會被忽略。For example if you apply [AllowAnonymous] at the controller level, any [Authorize] attributes on the same controller (or on any action within it) is ignored.