AspNetCore.Docs/aspnetcore/security/authorization/simple.md

70 lines
2.1 KiB
Markdown
Raw Normal View History

2016-10-29 01:35:15 +08:00
---
title: Simple authorization in ASP.NET Core
2016-10-29 01:35:15 +08:00
author: rick-anderson
description: Learn how to use the Authorize attribute to restrict access to ASP.NET Core controllers and actions.
2018-01-29 23:21:31 +08:00
ms.author: riande
2016-10-29 01:35:15 +08:00
ms.date: 10/14/2016
uid: security/authorization/simple
---
# Simple authorization in ASP.NET Core
2016-10-29 01:35:15 +08:00
2017-10-14 04:50:30 +08:00
<a name="security-authorization-simple"></a>
2016-10-29 01:35:15 +08:00
Authorization in MVC is controlled through the `AuthorizeAttribute` attribute and its various parameters. At its simplest, applying the `AuthorizeAttribute` attribute to a controller or action limits access to the controller or action to any authenticated user.
2016-10-29 01:35:15 +08:00
For example, the following code limits access to the `AccountController` to any authenticated user.
2016-11-18 13:03:07 +08:00
```csharp
2016-10-29 01:35:15 +08:00
[Authorize]
public class AccountController : Controller
{
public ActionResult Login()
{
}
2016-10-29 01:35:15 +08:00
public ActionResult Logout()
{
}
}
```
2016-10-29 01:35:15 +08:00
2017-12-07 05:05:16 +08:00
If you want to apply authorization to an action rather than the controller, apply the `AuthorizeAttribute` attribute to the action itself:
2016-10-29 01:35:15 +08:00
2016-11-18 13:03:07 +08:00
```csharp
2016-10-29 01:35:15 +08:00
public class AccountController : Controller
2017-12-07 05:05:16 +08:00
{
public ActionResult Login()
2016-10-29 01:35:15 +08:00
{
2017-12-07 05:05:16 +08:00
}
2016-10-29 01:35:15 +08:00
2017-12-07 05:05:16 +08:00
[Authorize]
public ActionResult Logout()
{
2016-10-29 01:35:15 +08:00
}
2017-12-07 05:05:16 +08:00
}
```
2016-10-29 01:35:15 +08:00
Now only authenticated users can access the `Logout` function.
2016-10-29 01:35:15 +08:00
You can also use the `AllowAnonymous` attribute to allow access by non-authenticated users to individual actions. For example:
2016-10-29 01:35:15 +08:00
2016-11-18 13:03:07 +08:00
```csharp
2016-10-29 01:35:15 +08:00
[Authorize]
public class AccountController : Controller
{
[AllowAnonymous]
public ActionResult Login()
{
}
2016-10-29 01:35:15 +08:00
public ActionResult Logout()
{
}
}
```
2016-10-29 01:35:15 +08:00
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.
> [!WARNING]
> `[AllowAnonymous]` bypasses all authorization statements. If you combine `[AllowAnonymous]` and any `[Authorize]` attribute, the `[Authorize]` attributes are ignored. 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.