Policy-Based Authorization

Get familiar with how policy-based authorization works in ASP.NET Core.

Policy-based authorization works by configuring specific authorization rules that can be as simple or as complex as we want them to be. For example, while a role-based authorization only relies on specific roles being present in the access token, policy-based authorization can be applied in the following ways:

  • When the presence of specific roles is required

  • When the presence of any custom or standard claims is required

  • When a combination of specific roles, claims, etc., is required to be present

  • When a complex custom calculation based on any data in the access token must be applied

In this lesson, we will explore several examples of configuring an authorization policy. All of these are demonstrated by the following playground:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace DemoApp.Controllers;

[Authorize("has_admin_role")]
[Route("api/[controller]")]
[ApiController]
public class InfoController : ControllerBase
{
    [HttpGet()]
    public IActionResult GetSecretInfo()
    {
        return Ok("Secret info delivered.");
    }

    [AllowAnonymous]
    [HttpGet("health")]
    public IActionResult GetEndpointHealth()
    {
        return Ok("The endpoint is working");
    }
}
Role-based authorization demo

In this example, we have the InfoController.cs file in the Controllers folder. This controller has two endpoints:

  • api/info: It corresponds to the GetSecretInfo method on line 12.

  • api/info/health: It corresponds to the GetEndpointHealth method on line 19.

Using the AddAuthorization method

If we open the Program.cs ...