An authorization filter controls access to an MVC action or Razor Page. Authorization asks what a user may access; authentication determines who made the request. Authorization filters run first in the MVC filter pipeline, so a rejected request never reaches the action or page handler. section 22.1.1 section 21.1
For most applications, use ASP.NET Core’s built-in authorization framework rather than writing a custom filter. Adding [Authorize] uses its AuthorizeFilter: in the simplest case, an unauthenticated request is short-circuited with a 401 Unauthorized response. Custom policies can express more specific access requirements. section 22.1.1
Listing 22.3 Adding [Authorize] to an action method
public class RecipeApiController : ControllerBase
{
public IActionResult Get(int id) #1
{
// method body
}
[Authorize] #2
public IActionResult Edit( #3
int id, [FromBody] UpdateRecipeCommand command) #3
{
// method body
}
}
The recipe API example places [Authorize] on Edit, leaving Get without the attribute. Move the attribute to the controller to protect all its actions. section 22.1.1
Apply [Authorize] to an action, a controller, a Razor Page, or globally, depending on what needs protection. A custom synchronous authorization filter implements IAuthorizationFilter; its asynchronous counterpart implements IAsyncAuthorizationFilter. Choose one interface, not both, and prefer the built-in framework for authorization checks. section 22.1.1 section 21.4
A custom authorization filter can short-circuit by setting context.Result. When it does, ordinary result filters do not run; only IAlwaysRunResultFilter implementations run before the result executes. This differs from short-circuiting at later filter stages. section 22.2
