| Authentication-Entra-ID :👈 | 👉:Memory-Management-GC |
ASP.NET Core Custom Authorization Policies and Resource-Based Authorization |
ASP.NET Core Custom Authorization Policies and Resource-Based Authorization
1. Introduction
Authorization determines what an authenticated user is allowed to do inside an application.
For example, after a user logs in, the application may need to decide:
- Can this user access the Admin section?
- Can this user approve an order?
- Can this user edit a particular document?
- Can this user view another employee's information?
- Can this user delete a particular record?
ASP.NET Core provides several authorization approaches:
- Role-based authorization
- Claims-based authorization
- Policy-based authorization
- Custom authorization requirements and handlers
- Resource-based authorization
For enterprise applications, policy-based and resource-based authorization are particularly useful because they allow authorization rules to be centralized, reusable, and testable.
2. Authentication vs Authorization
Authentication and authorization solve two different problems.
| Authentication | Authorization |
|---|---|
| Identifies the user. | Determines what the user can do. |
| Who are you? | What are you allowed to access? |
| Usually performed through login, tokens, or external identity providers. | Performed through roles, claims, policies, and resource checks. |
| Example: User successfully signs in. | Example: User can approve an order. |
Authentication and Authorization Flow
Important: Authentication must be configured before authorization middleware in the ASP.NET Core request pipeline.
3. Types of Authorization in ASP.NET Core
3.1 Role-Based Authorization
Role-based authorization checks whether a user belongs to a particular role.
Example:
[Authorize(Roles = "Admin")]
public IActionResult DeleteUser(int id)
{
return Ok("User deleted");
}
Only users belonging to the Admin role can access this action.
You can also allow multiple roles:
[Authorize(Roles = "Admin,Manager")]
public IActionResult ViewReports()
{
return Ok();
}
This allows users who belong to either Admin or Manager.
Limitations of Role-Based Authorization
- It is difficult to represent detailed permissions using only roles.
- Users may need different permissions for different records.
- Authorization logic can become difficult to maintain when roles grow.
- Roles alone cannot determine whether a user owns a particular resource.
3.2 Claims-Based Authorization
A claim is a piece of information about a user.
Examples include:
- User ID
- Email address
- Department
- Country
- Permission
- Employee type
Example claims:
new Claim(ClaimTypes.Name, "John"),
new Claim(ClaimTypes.Email, "john@example.com"),
new Claim("Department", "Finance"),
new Claim("Permission", "Order.Approve")
Check a claim using the Authorize attribute:
[Authorize(Policy = "FinanceDepartment")]
public IActionResult FinanceReports()
{
return Ok();
}
Claims provide additional information that can be used when evaluating authorization policies.
4. What Is Policy-Based Authorization?
Policy-based authorization allows developers to define reusable authorization rules in one central location.
A policy can contain one or more requirements. ASP.NET Core evaluates these requirements before allowing access.
For example:
- Only users from the Finance department can access finance reports.
- Only users with the Order.Approve permission can approve orders.
- Only users with a particular claim and role can access a sensitive endpoint.
Policy-Based Authorization Flow
In a normal policy evaluation, all requirements must succeed for authorization to succeed. A custom handler can also explicitly fail a requirement or the authorization context.
5. Creating a Custom Authorization Policy
Let's create a policy that allows only users from the Finance department to access finance reports.
Step 1: Register the Policy
Open Program.cs.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddAuthentication();
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("FinanceDepartment", policy =>
{
policy.RequireClaim("Department", "Finance");
});
});
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Note: Add your actual authentication scheme configuration, such as JWT Bearer or Microsoft Entra ID, instead of relying on the parameterless authentication registration in a real application.
Step 2: Apply the Policy
[Authorize(Policy = "FinanceDepartment")]
[HttpGet("finance-reports")]
public IActionResult GetFinanceReports()
{
return Ok("Finance reports");
}
Now the user must have the claim:
Department = Finance
Otherwise, access is denied.
6. Built-In Authorization Requirements
ASP.NET Core provides several built-in methods for creating policies.
| Method | Purpose |
|---|---|
| RequireAuthenticatedUser() | Requires an authenticated user. |
| RequireRole() | Requires membership in one or more roles. |
| RequireClaim() | Requires a particular claim. |
| RequireUserName() | Requires a specific username. |
| RequireAssertion() | Allows a custom Boolean authorization expression. |
| Requirements and handlers | Support reusable and more complex authorization logic. |
Example: Combining Requirements
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("SeniorFinanceManager", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireRole("Manager");
policy.RequireClaim("Department", "Finance");
policy.RequireClaim("Level", "Senior");
});
});
The user must satisfy all these requirements.
7. Custom Authorization Requirements and Handlers
Built-in requirements are sufficient for simple conditions. For complex business rules, create custom authorization requirements and handlers.
A requirement describes what must be satisfied. A handler contains the logic that evaluates the requirement.
Architecture
Step 1: Create a Custom Requirement
Example: A user must be at least 18 years old to access a particular feature.
using Microsoft.AspNetCore.Authorization;
public class MinimumAgeRequirement : IAuthorizationRequirement
{
public int MinimumAge { get; }
public MinimumAgeRequirement(int minimumAge)
{
MinimumAge = minimumAge;
}
}
This class stores the minimum age required by the policy.
Step 2: Create the Authorization Handler
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
public class MinimumAgeHandler
: AuthorizationHandler<MinimumAgeRequirement>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
MinimumAgeRequirement requirement)
{
var dateOfBirthClaim = context.User.FindFirst(
ClaimTypes.DateOfBirth);
if (dateOfBirthClaim == null)
{
return Task.CompletedTask;
}
if (!DateTime.TryParse(
dateOfBirthClaim.Value, out var dateOfBirth))
{
return Task.CompletedTask;
}
var today = DateTime.UtcNow.Date;
var age = today.Year - dateOfBirth.Year;
if (dateOfBirth.Date > today.AddYears(-age))
{
age--;
}
if (age >= requirement.MinimumAge)
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
The handler reads the date-of-birth claim, calculates the age, and calls Succeed() if the requirement is satisfied.
Step 3: Register the Handler and Policy
builder.Services.AddSingleton<IAuthorizationHandler,
MinimumAgeHandler>();
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("MinimumAge18", policy =>
{
policy.RequireAuthenticatedUser();
policy.AddRequirements(
new MinimumAgeRequirement(18));
});
});
This example uses a singleton handler because it does not depend on scoped services. If a handler needs a scoped service, such as a DbContext, register it with an appropriate scoped lifetime.
Step 4: Apply the Policy
[Authorize(Policy = "MinimumAge18")]
[HttpGet("restricted-feature")]
public IActionResult GetRestrictedFeature()
{
return Ok("Access granted");
}
Only authenticated users whose date-of-birth claim satisfies the minimum-age requirement can access the endpoint.
Production consideration: Do not treat an unverified date-of-birth claim as trustworthy. The claim must come from a trusted identity source or a validated application data source.
8. What Is Resource-Based Authorization?
Resource-based authorization checks whether a user is allowed to perform an operation on a specific resource.
A resource can be:
- Document
- Order
- Employee record
- Customer profile
- Project
- Invoice
Example:
Suppose an application contains thousands of documents. A user should be allowed to edit only documents they own.
A simple role-based check such as Admin or User is not enough to determine whether the user owns a particular document.
Resource-based authorization checks the actual document and the current user.
Role-Based vs Resource-Based Authorization
| Role-Based | Resource-Based |
|---|---|
| Checks the user's role. | Checks the user against a particular resource. |
| Example: Admin can delete records. | Example: Owner can edit their document. |
| Usually applied through Authorize attributes. | Usually evaluated after loading the resource. |
| Does not automatically check resource ownership. | Can check ownership, department, status, or other resource-specific rules. |
9. Implementing Resource-Based Authorization
Let's build a document management example.
Business rule:
- A document has an ID and an OwnerId.
- The owner can edit their document.
- An administrator can edit any document.
- Other users cannot edit the document.
Step 1: Create the Document Model
public class Document
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
public string OwnerId { get; set; } = string.Empty;
}
Step 2: Define an Operation
ASP.NET Core provides an OperationAuthorizationRequirement class for representing operations on resources.
using Microsoft.AspNetCore.Authorization.Infrastructure;
public static class DocumentOperations
{
public static readonly OperationAuthorizationRequirement Read =
new() { Name = "Read" };
public static readonly OperationAuthorizationRequirement Update =
new() { Name = "Update" };
public static readonly OperationAuthorizationRequirement Delete =
new() { Name = "Delete" };
}
Step 3: Create the Resource Authorization Handler
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Infrastructure;
using System.Security.Claims;
public class DocumentAuthorizationHandler :
AuthorizationHandler<OperationAuthorizationRequirement, Document>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
OperationAuthorizationRequirement requirement,
Document resource)
{
var userId = context.User.FindFirst(
ClaimTypes.NameIdentifier)?.Value;
if (userId == null)
{
return Task.CompletedTask;
}
if (requirement.Name == "Read")
{
if (resource.OwnerId == userId ||
context.User.IsInRole("Admin"))
{
context.Succeed(requirement);
}
}
if (requirement.Name == "Update")
{
if (resource.OwnerId == userId ||
context.User.IsInRole("Admin"))
{
context.Succeed(requirement);
}
}
if (requirement.Name == "Delete")
{
if (context.User.IsInRole("Admin"))
{
context.Succeed(requirement);
}
}
return Task.CompletedTask;
}
}
This handler checks the requested operation, the user's identity, and the document's owner.
Step 4: Register the Handler
builder.Services.AddScoped<IAuthorizationHandler,
DocumentAuthorizationHandler>();
builder.Services.AddAuthorization();
The handler is scoped here because resource authorization handlers may need scoped dependencies in real applications.
Step 5: Inject IAuthorizationService into the Controller
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
[ApiController]
[Route("api/documents")]
public class DocumentsController : ControllerBase
{
private readonly IAuthorizationService _authorizationService;
private readonly IDocumentRepository _repository;
public DocumentsController(
IAuthorizationService authorizationService,
IDocumentRepository repository)
{
_authorizationService = authorizationService;
_repository = repository;
}
[HttpPut("{id:int}")]
public async Task<IActionResult> UpdateDocument(
int id,
UpdateDocumentRequest request)
{
var document = await _repository.GetByIdAsync(id);
if (document == null)
{
return NotFound();
}
var authorizationResult =
await _authorizationService.AuthorizeAsync(
User,
document,
DocumentOperations.Update);
if (!authorizationResult.Succeeded)
{
return Forbid();
}
document.Title = request.Title;
await _repository.SaveChangesAsync();
return Ok(document);
}
}
Important: The controller loads the document before calling AuthorizeAsync because the authorization decision depends on the document's OwnerId.
The example assumes that IDocumentRepository and UpdateDocumentRequest are defined elsewhere in the application.
10. Why the Authorize Attribute Is Not Enough for Resource-Based Authorization
Consider this endpoint:
[Authorize]
[HttpPut("{id}")]
public IActionResult UpdateDocument(int id)
{
// Load document here
}
The Authorize attribute runs before the action method executes. At that point, the document has not yet been loaded.
Therefore, the attribute cannot directly inspect the loaded document to check its owner.
For resource-based authorization, use IAuthorizationService after loading the resource.
var result = await _authorizationService.AuthorizeAsync(
User,
document,
DocumentOperations.Update);
11. Resource-Based Authorization with Custom Requirements
You are not limited to OperationAuthorizationRequirement. You can create your own requirement for a specific business rule.
For example, only the manager of a project can approve it.
Project Model
public class Project
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string ManagerId { get; set; } = string.Empty;
public string Status { get; set; } = string.Empty;
}
Custom Requirement
public class ProjectApprovalRequirement
: IAuthorizationRequirement
{
}
Custom Handler
public class ProjectApprovalHandler :
AuthorizationHandler<ProjectApprovalRequirement, Project>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
ProjectApprovalRequirement requirement,
Project resource)
{
var userId = context.User.FindFirst(
ClaimTypes.NameIdentifier)?.Value;
if (userId == resource.ManagerId &&
resource.Status == "Pending")
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
Register the Policy
builder.Services.AddScoped<IAuthorizationHandler,
ProjectApprovalHandler>();
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("CanApproveProject", policy =>
{
policy.Requirements.Add(
new ProjectApprovalRequirement());
});
});
Use the Policy with a Resource
var result = await _authorizationService.AuthorizeAsync(
User,
project,
"CanApproveProject");
if (!result.Succeeded)
{
return Forbid();
}
The authorization succeeds only when the user is the project manager and the project is pending.
12. Using RequireAssertion for Simple Custom Rules
For simple authorization conditions, RequireAssertion can avoid creating a separate requirement and handler.
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("CompanyEmail", policy =>
{
policy.RequireAssertion(context =>
context.User.Identity?.IsAuthenticated == true &&
context.User.HasClaim(
ClaimTypes.Email,
"admin@example.com"));
});
});
Apply the policy:
[Authorize(Policy = "CompanyEmail")]
public IActionResult GetCompanyData()
{
return Ok();
}
Use RequireAssertion for small, straightforward rules. Prefer custom requirements and handlers for complex logic that needs reuse, testing, or resource access.
13. Multiple Requirements and Multiple Handlers
A policy can contain multiple requirements.
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("OrderApproval", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireRole("Manager");
policy.RequireClaim("Department", "Sales");
policy.AddRequirements(
new MinimumApprovalLevelRequirement(2));
});
});
In this example, the user must:
- Be authenticated.
- Have the Manager role.
- Belong to the Sales department.
- Satisfy the minimum approval-level requirement.
By default, all requirements must succeed. If a requirement has multiple handlers, any handler that successfully satisfies that requirement can mark it as succeeded.
14. Handling Authorization in Minimal APIs
Authorization policies can also be applied to Minimal APIs.
Policy Registration
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly", policy =>
{
policy.RequireRole("Admin");
});
});
Apply Policy to an Endpoint
app.MapGet("/admin/reports", () =>
{
return Results.Ok("Admin reports");
})
.RequireAuthorization("AdminOnly");
Resource-Based Authorization in Minimal APIs
app.MapPut("/documents/{id:int}", async (
int id,
UpdateDocumentRequest request,
ClaimsPrincipal user,
IAuthorizationService authorizationService,
IDocumentRepository repository) =>
{
var document = await repository.GetByIdAsync(id);
if (document == null)
{
return Results.NotFound();
}
var result = await authorizationService.AuthorizeAsync(
user,
document,
DocumentOperations.Update);
if (!result.Succeeded)
{
return Results.Forbid();
}
document.Title = request.Title;
await repository.SaveChangesAsync();
return Results.Ok(document);
})
.RequireAuthorization();
The endpoint requires an authenticated user, loads the document, and then performs the resource-specific authorization check.
15. Dynamic Authorization Policies
Sometimes an application has many permissions, such as:
- Orders.Read
- Orders.Create
- Orders.Update
- Orders.Delete
- Users.Read
- Users.Update
Creating a separate policy manually for every permission may become difficult to maintain.
A custom IAuthorizationPolicyProvider can generate policies dynamically based on policy names.
Example: Permission Requirement
public class PermissionRequirement : IAuthorizationRequirement
{
public string Permission { get; }
public PermissionRequirement(string permission)
{
Permission = permission;
}
}
Permission Handler
public class PermissionHandler
: AuthorizationHandler<PermissionRequirement>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
PermissionRequirement requirement)
{
if (context.User.HasClaim(
"Permission", requirement.Permission))
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
Dynamic Policy Provider
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Options;
public class PermissionPolicyProvider
: IAuthorizationPolicyProvider
{
private const string Prefix = "Permission:";
private readonly DefaultAuthorizationPolicyProvider _fallback;
public PermissionPolicyProvider(
IOptions<AuthorizationOptions> options)
{
_fallback = new DefaultAuthorizationPolicyProvider(options);
}
public Task<AuthorizationPolicy> GetDefaultPolicyAsync()
{
return _fallback.GetDefaultPolicyAsync();
}
public Task<AuthorizationPolicy?> GetFallbackPolicyAsync()
{
return _fallback.GetFallbackPolicyAsync();
}
public Task<AuthorizationPolicy?> GetPolicyAsync(
string policyName)
{
if (!policyName.StartsWith(
Prefix, StringComparison.OrdinalIgnoreCase))
{
return _fallback.GetPolicyAsync(policyName);
}
var permission = policyName[Prefix.Length..];
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.AddRequirements(
new PermissionRequirement(permission))
.Build();
return Task.FromResult<AuthorizationPolicy?>(policy);
}
}
Register Services
builder.Services.AddSingleton<IAuthorizationPolicyProvider,
PermissionPolicyProvider>();
builder.Services.AddScoped<IAuthorizationHandler,
PermissionHandler>();
builder.Services.AddAuthorization();
Use Dynamic Policies
[Authorize(Policy = "Permission:Orders.Read")]
[HttpGet("orders")]
public IActionResult GetOrders()
{
return Ok();
}
[Authorize(Policy = "Permission:Orders.Delete")]
[HttpDelete("orders/{id}")]
public IActionResult DeleteOrder(int id)
{
return Ok();
}
The policy provider extracts the permission name and creates the corresponding policy.
Production considerations:
- Validate policy names and reject empty permission names.
- Use a consistent permission naming convention.
- Keep the policy provider deterministic and lightweight.
- Load permissions from a trusted source.
- Consider caching permission data where appropriate.
- Do not trust permission values supplied directly by an untrusted client.
16. Authorization with Database-Stored Permissions
In enterprise applications, permissions are often stored in a database rather than embedded individually in user tokens.
Example database structure:
| Table | Purpose |
|---|---|
| Users | Stores user information. |
| Roles | Stores application roles. |
| Permissions | Stores individual permissions. |
| UserRoles | Maps users to roles. |
| RolePermissions | Maps roles to permissions. |
Authorization Flow
A typical implementation uses a permission service to retrieve permissions for the current user. The authorization handler calls this service to evaluate the requested permission.
Important design considerations:
- Use a dedicated service rather than putting database queries directly into controllers.
- Cache permission data carefully to reduce repeated database lookups.
- Define how permission changes invalidate cached values.
- Use scoped dependencies appropriately.
- Ensure that permission changes take effect within an acceptable time.
17. Authorization Result: Challenge vs Forbid
ASP.NET Core distinguishes between authentication failure and authorization failure.
| Result | Meaning | Typical HTTP response |
|---|---|---|
| Challenge | The user is not authenticated or has not satisfied the authentication scheme. | 401 Unauthorized for bearer authentication; redirects may be used by cookie authentication. |
| Forbid | The user is authenticated but is not allowed to access the resource. | 403 Forbidden for bearer authentication. |
Example:
if (!User.Identity?.IsAuthenticated ?? true)
{
return Challenge();
}
if (!authorizationResult.Succeeded)
{
return Forbid();
}
When using a resource authorization check, the application normally assumes the user has already passed authentication. If the resource check fails, return Forbid rather than treating the user as unauthenticated.
18. Authorization Middleware Order
Middleware order matters in ASP.NET Core.
var app = builder.Build();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Authentication should run before authorization so that the authorization system can evaluate the authenticated user's identity and claims.
19. Global Authorization and Fallback Policies
In many enterprise applications, endpoints should require authentication by default.
A fallback policy can enforce this behavior.
builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy =
new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
});
With this configuration, endpoints without explicit authorization metadata require an authenticated user.
For public endpoints, use AllowAnonymous:
[AllowAnonymous]
[HttpGet("public-information")]
public IActionResult GetPublicInformation()
{
return Ok("Public information");
}
Do not confuse a fallback policy with the default policy. The default policy is commonly used when authorization is required without naming a specific policy. The fallback policy applies when an endpoint has no authorization metadata.
20. Security Best Practices
20.1 Always Validate Resource Ownership
Do not assume that a user can access a record just because they know its ID.
Always verify ownership or another appropriate access rule.
20.2 Do Not Trust Client-Supplied Roles or Permissions
Never accept a role or permission from request data as proof of authorization.
Use claims from a trusted, validated authentication source or retrieve permissions from a trusted server-side store.
20.3 Keep Authorization Logic Centralized
Avoid repeating permission checks across multiple controllers.
Use policies and handlers so that the same business rule can be reused.
20.4 Apply the Principle of Least Privilege
Users should receive only the permissions required to perform their responsibilities.
20.5 Avoid Exposing Sensitive Resource Information
Consider whether returning NotFound instead of Forbid is appropriate when revealing the existence of a resource could expose sensitive information. Apply a consistent policy based on the application's security requirements.
20.6 Protect Against Insecure Direct Object References
Insecure Direct Object Reference (IDOR) occurs when an application allows users to access records simply by changing an identifier in a request.
For example:
GET /api/documents/100
GET /api/documents/101
GET /api/documents/102
Never assume that knowing a document ID grants access to that document. Check authorization for every requested resource.
20.7 Be Careful with Cached Permissions
If permissions are cached, revoked permissions may remain effective until the cache expires or is invalidated.
For sensitive operations, design permission revocation and cache invalidation carefully.
20.8 Test Authorization Rules
Test both allowed and denied scenarios, including users with missing claims, incorrect roles, invalid resource ownership, and revoked permissions.
21. Common Authorization Mistakes
| Mistake | Why It Is a Problem | Better Approach |
|---|---|---|
| Using only roles for every rule | Cannot represent all resource-specific rules. | Use policies and resource-based handlers. |
| Checking ownership only in the UI | API requests can bypass the UI. | Validate on the server. |
| Trusting client-provided permissions | Clients can manipulate request data. | Use trusted claims or server-side permission storage. |
| Putting all logic in controllers | Creates duplication and difficult maintenance. | Use authorization handlers. |
| Using the Authorize attribute for loaded-resource checks | The resource may not yet be available. | Use IAuthorizationService after loading it. |
| Ignoring permission revocation | Cached or long-lived claims may preserve old access. | Design appropriate invalidation and token lifetimes. |
| Returning success after a failed check | Creates an authorization vulnerability. | Stop processing and return an appropriate denial response. |
22. Unit Testing Authorization Handlers
Authorization handlers should be tested independently of controllers wherever possible.
Example Test for Document Ownership
[Fact]
public async Task Owner_Can_Update_Document()
{
var user = new ClaimsPrincipal(
new ClaimsIdentity(
new[]
{
new Claim(ClaimTypes.NameIdentifier, "user-100")
},
"Test"));
var document = new Document
{
Id = 1,
Title = "Report",
OwnerId = "user-100"
};
var handler = new DocumentAuthorizationHandler();
var requirement = DocumentOperations.Update;
var context = new AuthorizationHandlerContext(
new[] { requirement },
user,
document);
await handler.HandleAsync(context);
Assert.True(context.HasSucceeded);
}
This test verifies that the document owner can update their document.
Example Test for a Different User
[Fact]
public async Task NonOwner_Cannot_Update_Document()
{
var user = new ClaimsPrincipal(
new ClaimsIdentity(
new[]
{
new Claim(ClaimTypes.NameIdentifier, "user-200")
},
"Test"));
var document = new Document
{
Id = 1,
Title = "Report",
OwnerId = "user-100"
};
var handler = new DocumentAuthorizationHandler();
var context = new AuthorizationHandlerContext(
new[] { DocumentOperations.Update },
user,
document);
await handler.HandleAsync(context);
Assert.False(context.HasSucceeded);
}
Also test administrator access, missing user identifiers, unsupported operations, and other business-rule boundaries.
23. Enterprise-Level Authorization Architecture
A larger application may separate authorization into distinct layers:
- Authentication: identifies the user.
- Claims and roles: provide identity and role information.
- Authorization policies: define reusable access rules.
- Authorization handlers: evaluate requirements.
- Permission service: retrieves application-specific permissions.
- Resource repository: loads the requested resource.
- Database: stores users, roles, permissions, and resource ownership.
This architecture separates identity, authorization rules, permission retrieval, and resource access. It makes large applications easier to maintain and test.
24. When Should You Use Each Authorization Approach?
| Scenario | Recommended Approach |
|---|---|
| Only administrators can access an endpoint. | Role-based authorization |
| Only Finance department users can access reports. | Claims-based or policy-based authorization |
| Users need specific application permissions. | Custom policy and permission handler |
| Only the document owner can edit a document. | Resource-based authorization |
| Only a project manager can approve a pending project. | Resource-based authorization with a custom requirement |
| Permissions are managed dynamically in a database. | Permission service and custom policy provider or handler |
25. Interview Questions and Answers
Q1. What is authorization in ASP.NET Core?
Authorization determines whether an authenticated user has permission to access a resource or perform an operation.
Q2. What is policy-based authorization?
It is an authorization approach where reusable policies contain requirements that must be satisfied before access is granted.
Q3. What is an authorization requirement?
An authorization requirement represents a condition that must be satisfied. It implements IAuthorizationRequirement.
Q4. What is an authorization handler?
An authorization handler evaluates a requirement and calls context.Succeed(requirement) when the condition is satisfied.
Q5. What is resource-based authorization?
It checks whether a user can perform a specific operation on a particular resource, such as editing a document they own.
Q6. What is IAuthorizationService?
It is the ASP.NET Core service used to evaluate authorization against a user, a resource, and optionally a named policy or requirement.
Q7. What is the difference between roles and claims?
Roles represent user membership in groups such as Admin or Manager. Claims represent individual facts or attributes about a user, such as department or permission.
Q8. What is the difference between policy-based and resource-based authorization?
Policy-based authorization evaluates requirements defined by a policy. Resource-based authorization evaluates access to a particular resource, often using IAuthorizationService after the resource is loaded. Resource-based authorization can also use named policies and custom requirements.
Q9. Can we use multiple requirements in one policy?
Yes. By default, all requirements in a policy must succeed for authorization to succeed.
Q10. What is RequireAssertion?
RequireAssertion allows a developer to define a simple custom authorization condition using a Boolean expression.
Q11. Why can't we always use the Authorize attribute for resource-based authorization?
The attribute is evaluated before the action loads the resource. For resource-specific checks, the application usually needs to load the resource first and then call IAuthorizationService.
Q12. What is the difference between Challenge and Forbid?
Challenge means the user needs to authenticate or satisfy the authentication scheme. Forbid means the user is authenticated but does not have permission.
Q13. What is a custom authorization policy provider?
It implements IAuthorizationPolicyProvider and can create policies dynamically, for example from permission names.
Q14. Can authorization handlers use dependency injection?
Yes. Handlers can receive services through constructor injection. Their service lifetimes must be compatible with the dependencies they use.
Q15. How do you prevent IDOR vulnerabilities?
Do not trust resource IDs supplied by clients. Load the requested resource and verify the current user's permission to access it on the server.
26. Final Best-Practice Checklist
- Configure authentication before authorization middleware.
- Use roles for broad access categories.
- Use claims for user attributes and permissions.
- Use policies for reusable authorization rules.
- Use custom requirements and handlers for complex business rules.
- Use resource-based authorization for ownership and record-specific access.
- Use IAuthorizationService when authorization depends on a loaded resource.
- Never rely only on frontend authorization.
- Never trust client-supplied roles or permissions.
- Use least-privilege permissions.
- Plan permission caching and revocation carefully.
- Test both successful and unsuccessful authorization scenarios.
27. Official Microsoft Documentation
| Authentication-Entra-ID :👈 | 👉:Memory-Management-GC |