Policy-Based Authorization
Explore the implementation of policy-based authorization in ASP.NET Core using JWT access tokens. Understand how to configure authorization policies that check roles, claims, or custom requirements. Learn to create custom authorization handlers and apply policies to secure API endpoints effectively.
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");
}
}In this example, we have the InfoController.cs file in the Controllers folder. This controller has two endpoints:
api/info: It corresponds to theGetSecretInfomethod on line 12.api/info/health: It corresponds to theGetEndpointHealthmethod on line 19.
Using the AddAuthorization method
If we open the Program.cs ...