liveBook · Manning

Authorization filter

As explained in ASP.NET Core in Action, 3e

IAuthorizationFilter is an ASP.NET Core MVC interface for synchronous filters that perform authorization checks.

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

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains execution order, [Authorize] scopes, interface choices, and short-circuit behavior; defers detailed authorization requirements.
Examples
Uses a recipe API controller with [Authorize] on its Edit action but not its Get action.
What it assumes
Builds on MVC actions and the filter pipeline while defining authentication and authorization before applying them.
What you can do after
Apply it via [Authorize] to protect an action, controller, or Razor Page, and recognize when access denial stops execution.
How it connects
Connects authentication, authorization policies, the MVC filter pipeline, Razor Pages, and result filters.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.