How to use policy-based authorization in ASP.NET Core
By FoxLearn 1/4/2025 3:17:13 AM 36
While role-based authorization assigns permissions based on user roles, policy-based authorization offers a more flexible and loosely coupled security model, allowing developers to define custom authorization logic through policies.
In a policy-based security model, there are three key concepts: policy, requirement, and handler.
- A policy consists of requirements, which are made up of parameters that identify a user's credentials.
- A handler evaluates the user's authorization, determining which resources the user can access based on the policy and its requirements.
Register a policy in ASP.NET Core
A policy in ASP.Net Core is registered in the ConfigureServices method of the Startup.cs file.
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddAuthorization(options => { options.AddPolicy("CustomAgePolicy", policy => policy.Requirements.Add(new MinimumAgeRequirement(18))); }); }
Implement a policy requirement class in ASP.NET Core
public class MinimumAgeRequirement : IAuthorizationRequirement { public MinimumAgeRequirement(int age) { MinimumAge = age; } protected int MinimumAge { get; set; } }
This class defines a custom requirement called MinimumAgeRequirement, which accepts an integer representing the minimum age required for authorization.
Implement a policy handler class in ASP.NET Core
public class MinimumAgeHandler : AuthorizationHandler<MinimumAgeRequirement> { protected override Task HandleRequirementAsync(AuthorizationContext context, MinimumAgeRequirement requirement) { if (!context.User.HasClaim(c => c.Type == ClaimTypes.DateOfBirth)) { return Task.CompletedTask; } var dob = Convert.ToDateTime(context.User.FindFirst(c => c.Type == ClaimTypes.DateOfBirth).Value); var age = DateTime.Now.Year - dob.Year; if (dob > DateTime.Now.AddYears(-age)) age--; if (age >= requirement.MinimumAge) { context.Succeed(requirement); } return Task.CompletedTask; } }
In this example, the MinimumAgeHandler evaluates the DateOfBirth claim of the user and checks if their age meets or exceeds the minimum required age.
Applying the Authorization Policy
To apply this policy in your application, you would use the [Authorize] attribute like this:
[Authorize(Policy = "CustomAgePolicy")] public class ProfileController : Controller { // Controller actions go here... }
Here, the ProfileController is protected by the CustomAgePolicy, meaning that only users who meet the age requirement will be authorized to access its actions.
- How to use TinyIoC in ASP.NET Core
- How to use FusionCache in ASP.NET Core
- How to use Brotli for response compression in ASP.NET Core
- How to use SignalR in ASP.NET Core
- How to use the Dapper ORM in ASP.NET Core
- How to enable CORS in ASP.NET Core
- How to implement HTTP.sys web server in ASP.NET Core
- How to use File Providers in ASP.NET Core