Simple authorization in ASP.NET Core

Authorization in ASP.NET Core is controlled with AuthorizeAttribute and its various parameters. In its simplest form, applying the [Authorize] attribute to a controller, action, or Razor Page, limits access to that component to any authenticated user.

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()
    {
    }
}

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()
   {
   }
}

Now only authenticated users can access the Logout function.

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()
    {
    }
}

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.