Verifying who is calling an API is not the same as deciding what that caller may do. Authentication establishes an identity from a trusted credential. Authorization evaluates whether that identity is allowed to access a particular endpoint, operation, or resource. Treating authentication as permission often creates APIs where any signed-in user can perform sensitive actions.
ASP.NET Core provides a policy-based authorization model built around requirements, policies, and handlers. This model works for simple permission checks as well as rules that depend on the specific resource being accessed. This article combines JWT bearer validation, claim-based policies, and resource-based authorization into a practical design.
Keep authentication and authorization separate
A bearer token should not be accepted merely because it can be decoded. An API must validate its signature, issuer, audience, and expiration. When validation succeeds, ASP.NET Core creates a ClaimsPrincipal representing the caller.
Authorization then evaluates that principal. For example, a token might contain department=finance or permission=reports.read. A claim is information about the subject; it is not automatically a permission. The application must define how a claim participates in an authorization policy and where that policy applies.
Configure JWT bearer validation
APIs commonly use the Microsoft.AspNetCore.Authentication.JwtBearer package. The following configuration establishes JWT bearer authentication and defines the expected identity provider and audience:
using Microsoft.AspNetCore.Authentication.JwtBearer;
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = builder.Configuration["Auth:Authority"];
options.Audience = builder.Configuration["Auth:Audience"];
options.RequireHttpsMetadata = true;
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();Authority identifies the trusted authorization server that publishes metadata and signing keys. Audience restricts the token to the intended API. HTTPS metadata should remain enabled in production. If the signature, issuer, audience, or expiration is invalid, the API should not treat the token as an authenticated identity.
Express permissions as policies
Policies keep authorization rules named, centralized, and testable. Instead of scattering string comparisons throughout controllers, define a policy for a meaningful application capability:
builder.Services.AddAuthorizationBuilder()
.AddPolicy("Reports.Read", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireClaim("permission", "reports.read");
});Apply the policy to an MVC or API action with the Authorize attribute:
[Authorize(Policy = "Reports.Read")]
[HttpGet("reports")]
public IActionResult GetReports()
{
return Ok();
}For a Minimal API endpoint, use authorization metadata directly:
app.MapGet("/reports", () => Results.Ok())
.RequireAuthorization("Reports.Read");A policy can combine multiple requirements. For example, requiring an authenticated user and a specific permission makes both conditions explicit. Named policies also make it easier to review security decisions during code review and to test them independently of controller implementation details.
Roles, claims, and permissions
Roles such as Administrator or Support are useful for broad organizational categories. However, creating a new role for every endpoint capability can become difficult to manage. Claims can carry more detailed facts such as tenant identifiers, departments, subscription tiers, or permissions.
A permission-oriented vocabulary might include:
orders.readfor viewing orders,orders.writefor creating or updating orders,orders.deletefor deleting orders.
The important principle is consistency. The identity provider and the API must agree on claim types and values. Establish a central naming convention and avoid silently accepting several spellings for the same permission. Claim values can be case-sensitive in authorization comparisons, so inconsistent casing can produce surprising results.
Move from endpoint access to resource access
A policy can answer whether a caller has a general permission. Many business systems need a more specific answer: may this user access this particular order or document?
Suppose a user has orders.read, but should only see orders belonging to the user’s tenant. The endpoint-level policy alone cannot enforce that rule. After loading the resource, call IAuthorizationService with the resource and evaluate a custom requirement.
public sealed record OrderResource(Guid TenantId, Guid OwnerId);
public sealed class OrderAccessRequirement : IAuthorizationRequirement;
public sealed class OrderAccessHandler
: AuthorizationHandler<OrderAccessRequirement, OrderResource>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
OrderAccessRequirement requirement,
OrderResource resource)
{
var tenantId = context.User.FindFirst("tenant_id")?.Value;
var canRead = context.User.HasClaim("permission", "orders.read");
if (canRead && tenantId == resource.TenantId.ToString())
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}After registering the requirement and handler in an OrderAccess policy, a controller can evaluate the loaded object:
var order = await db.Orders.FindAsync(id);
if (order is null)
{
return NotFound();
}
var resource = new OrderResource(order.TenantId, order.OwnerId);
var result = await authorizationService.AuthorizeAsync(
User, resource, "OrderAccess");
if (!result.Succeeded)
{
return Forbid();
}
return Ok(order);This pattern is appropriate for tenant boundaries, ownership rules, approval states, and other decisions that depend on resource data. Keep handlers focused and avoid unnecessary database calls inside them. Also ensure that every relevant read and write path applies the same access rule.
Understand 401 and 403
A 401 Unauthorized response indicates that the request did not provide a valid authenticated identity, for example because the token was missing, expired, or failed validation. A 403 Forbidden response indicates that authentication succeeded but the caller does not satisfy the required authorization policy.
Preserving this distinction helps clients and monitoring systems diagnose expired credentials, incorrect audiences, and missing permissions without exposing sensitive token details.
Practical security checklist
- Validate the token signature, issuer, audience, and expiration.
- Keep authentication configuration separate from authorization rules.
- Use named policies instead of repeated claim comparisons in endpoints.
- Use custom requirements and handlers for resource-dependent rules.
- Enforce tenant and ownership boundaries on the server.
- Define permission and claim names as a shared contract.
- Log authorization failures without recording bearer tokens or sensitive claims.
- Test successful access, missing permissions, invalid identity, and cross-tenant attempts.
Conclusion
ASP.NET Core’s authorization model scales from a simple claim check to detailed resource-level decisions without requiring unrelated mechanisms. JWT validation establishes a trustworthy identity, policies describe general access conditions, and handlers evaluate rules that depend on the resource itself. Keeping these responsibilities distinct produces APIs that are easier to audit, test, and evolve.
0 Comments