Authorization
Authentication tells who the user is; authorization decides what that user may do. This note covers roles, claims, named policies, custom requirement handlers and resource-based checks in ASP.NET Core, plus the 401 vs 403 rule.
59.1 The problem: logged in, but no rules
- /admin/sales and /orders/{id} both use plain RequireAuthorization().
- Riya, a normal customer, gets 200 OK with the full sales figure.
- Riya also gets Kabir's order 2.
C#
var builder = WebApplication.CreateBuilder(args);builder.Services.AddAuthentication() .AddJwtBearer();builder.Services.AddAuthorization(); var app = builder.Build();app.MapGet("/admin/sales", () => new { Today = 184500 }) .RequireAuthorization();app.MapGet("/orders/{id:int}", (int id) => orders[id]) .RequireAuthorization();app.Run();Output
$ curl -i localhost:5059/admin/sales \ -H "Authorization: Bearer $RIYA"HTTP/1.1 200 OKContent-Type: application/json; charset=utf-8{"today":184500}$ curl -i localhost:5059/orders/2 \ -H "Authorization: Bearer $RIYA"HTTP/1.1 200 OKContent-Type: application/json; charset=utf-8{"id":2,"owner":"kabir","amount":499}59.2 401 vs 403
- Without a rule, RequireAuthorization() only checks that the user is authenticated (the token is valid).
- Authentication = who are you? Failure -> 401 Unauthorized.
- Authorization = what may you do? Failure -> 403 Forbidden.
| Point | 401 Unauthorized | 403 Forbidden |
|---|---|---|
| Question | Who are you? | What may you do? |
| Cause | No token, invalid or expired token | Known user, missing role / claim / ownership |
| Header | WWW-Authenticate: Bearer | None |
| Client should | Refresh token / log in again | Show "not allowed"; logging in again won't help |
59.3 Test tokens: dotnet user-jwts
- dotnet user-jwts creates signed development JWTs, no login endpoint needed.
- Riya: plan=premium. Aman: role Admin. Kabir: a 16-year-old customer. All carry a dob claim.
Terminal
dotnet user-jwts create --name riya \ --claim plan=premium --claim dob=2001-04-12 dotnet user-jwts create --name aman \ --role Admin --claim dob=1995-08-20 dotnet user-jwts create --name kabir \ --claim dob=2010-01-05Output
New JWT saved with ID 'bea0d361'.Name: amanRoles: [Admin]Custom Claims: [dob=1995-08-20]Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlx...59.4 Fix 1: roles
- RequireAuthorization(p => p.RequireRole("Admin")): the token must carry the Admin role.
- No token: 401. Riya: 403. Aman: 200.
- In controllers, [Authorize(Roles = "Admin")] on the class makes every action admin-only; [AllowAnonymous] on an action overrides it.
C#
app.MapGet("/admin/sales", () => new { Today = 184500 }) .RequireAuthorization(p => p.RequireRole("Admin"));Output
$ curl -i localhost:5059/admin/salesHTTP/1.1 401 UnauthorizedWWW-Authenticate: Bearer$ curl -i localhost:5059/admin/sales \ -H "Authorization: Bearer $RIYA"HTTP/1.1 403 Forbidden$ curl -i localhost:5059/admin/sales \ -H "Authorization: Bearer $AMAN"HTTP/1.1 200 OK{"today":184500}C#
[ApiController][Route("api/reports")][Authorize(Roles = "Admin")]public class ReportsController : ControllerBase{ [HttpGet("sales")] public object Sales() => new { Today = 184500 }; [AllowAnonymous] [HttpGet("status")] public string Status() => "Reports service up";}Output
$ curl -i localhost:5059/api/reports/sales \ -H "Authorization: Bearer $RIYA"HTTP/1.1 403 Forbidden$ curl -i localhost:5059/api/reports/statusHTTP/1.1 200 OKContent-Type: text/plain; charset=utf-8Reports service up59.5 Fix 2: claims and named policies
- When a rule depends on a user detail, roles are not enough; those details are claims in the token.
- AddAuthorizationBuilder().AddPolicy("Premium", p => p.RequireClaim("plan", "premium")).
- "Adult" uses a custom requirement (MinAgeRequirement(18)) whose logic lives in a handler.
- Endpoints just name the policy: Riya gets premium deals, Kabir gets 403.
C#
builder.Services.AddAuthorizationBuilder() .AddPolicy("Premium", p => p.RequireClaim("plan", "premium")) .AddPolicy("Adult", p => p.AddRequirements( new MinAgeRequirement(18)));builder.Services.AddSingleton< IAuthorizationHandler, MinAgeHandler>(); app.MapGet("/deals/premium", () => "Premium deals: 40% off") .RequireAuthorization("Premium"); app.MapPost("/checkout/emi", () => "EMI approved") .RequireAuthorization("Adult");Output
$ curl -i localhost:5059/deals/premium \ -H "Authorization: Bearer $RIYA"HTTP/1.1 200 OKPremium deals: 40% off$ curl -i localhost:5059/deals/premium \ -H "Authorization: Bearer $KABIR"HTTP/1.1 403 Forbidden59.6 Custom requirement handler
- MinAgeRequirement is a simple record implementing IAuthorizationRequirement.
- MinAgeHandler : AuthorizationHandler<MinAgeRequirement> reads the dob claim.
- dob + 18 years <= today -> ctx.Succeed(req). If Succeed is never called, the requirement fails.
- Riya's EMI is approved; Kabir gets 403.
C#
public class MinAgeHandler : AuthorizationHandler<MinAgeRequirement>{ protected override Task HandleRequirementAsync( AuthorizationHandlerContext ctx, MinAgeRequirement req) { var dob = ctx.User.FindFirst("dob"); if (dob is not null && DateTime.Parse( dob.Value).AddYears(req.Years) <= DateTime.Today) ctx.Succeed(req); return Task.CompletedTask; }}Output
$ curl -i -X POST localhost:5059/checkout/emi \ -H "Authorization: Bearer $RIYA"HTTP/1.1 200 OKEMI approved$ curl -i -X POST localhost:5059/checkout/emi \ -H "Authorization: Bearer $KABIR"HTTP/1.1 403 Forbidden59.7 Fix 3: resource-based authorization
- Rule depends on data: only the owner (or an admin) may see an order.
- An attribute cannot do this: when it runs, the order is not loaded yet.
- Inject IAuthorizationService, load the order, then AuthorizeAsync(user, order, "OrderOwner"); on failure return Results.Forbid() (403).
- OwnerHandler : AuthorizationHandler<OwnerRequirement, Order> receives the order: Admin or name == order.Owner -> Succeed.
- Both handlers are registered as singletons.
C#
app.MapGet("/orders/{id:int}", async (int id, ClaimsPrincipal user, IAuthorizationService auth) =>{ if (!orders.TryGetValue(id, out var order)) return Results.NotFound(); var result = await auth.AuthorizeAsync( user, order, "OrderOwner"); return result.Succeeded ? Results.Ok(order) : Results.Forbid();}).RequireAuthorization();C#
public class OwnerHandler : AuthorizationHandler< OwnerRequirement, Order>{ protected override Task HandleRequirementAsync( AuthorizationHandlerContext ctx, OwnerRequirement req, Order order) { var name = ctx.User.Identity?.Name; if (ctx.User.IsInRole("Admin") || name == order.Owner) ctx.Succeed(req); return Task.CompletedTask; }}Output
$ curl -i localhost:5059/orders/1 \ -H "Authorization: Bearer $RIYA"HTTP/1.1 200 OK{"id":1,"owner":"riya","amount":1299}$ curl -i localhost:5059/orders/2 \ -H "Authorization: Bearer $RIYA"HTTP/1.1 403 Forbidden$ curl -i localhost:5059/orders/2 \ -H "Authorization: Bearer $AMAN"HTTP/1.1 200 OK{"id":2,"owner":"kabir","amount":499}- Step 1
1.Authentication: token -> User with claims (fail = 401)
- Step 2
2.Endpoint policy: role / claim / requirement
- Step 3
3.Handlers: call Succeed, or not (fail = 403)
- Step 4
4.Endpoint code runs and loads the data
- Step 5
5.Resource check: IAuthorizationService.AuthorizeAsync, else Forbid
First who, then what
- Checkpoint: GET /orders/1 with no token returns 401, not 403: RequireAuthorization checks authentication first, so the endpoint code never runs.
59.8 Comparison: roles vs claims vs policies vs resource checks
| Tool | Checks | Example |
|---|---|---|
| RequireRole / [Authorize(Roles)] | A role claim | Admin-only sales report |
| RequireClaim (named policy) | A claim value | plan = premium -> premium deals |
| Custom requirement + handler | Any logic over claims | dob -> age >= 18 for EMI |
| IAuthorizationService.AuthorizeAsync | User + the loaded resource | Only the owner or an admin sees an order |
59.9 Common mistakes
- Treating plain RequireAuthorization() as security: it only means "logged in".
- Hard-coding a user-name check inside the endpoint and returning Unauthorized: Riya gets 401, and the client thinks her token expired and keeps sending her to log in.
- Fix: put the rule in a role policy; failure gives the correct 403.
- Thinking roles and claims are separate systems: a role is just a claim of type role; RequireRole / IsInRole check that claim, and [Authorize(Roles)] builds a policy under the hood.
C#
// Wrong: hard-coded check + 401app.MapGet("/admin/report", (ClaimsPrincipal user) =>{ if (user.Identity?.Name != "aman") return Results.Unauthorized(); return Results.Ok(new { Today = 184500 });});// Riya: HTTP/1.1 401 Unauthorized // Right: policy + 403app.MapGet("/admin/report", () => new { Today = 184500 }) .RequireAuthorization(p => p.RequireRole("Admin"));// Riya: HTTP/1.1 403 Forbidden59.10 Rules for authorization
- Give every endpoint a clear rule.
- Roles for big groups; detailed rules as claims and named policies.
- Keep rule logic in handlers.
- Check data rules with IAuthorizationService.
- Correct status: 401 for an unknown user, 403 for a known user.
59.11 Interview tips
- Keep authentication and authorization separate: unknown user = 401, no permission = 403.
- Roles for simple cases; named policies and custom requirements with handlers for the rest.
- Ownership checks: IAuthorizationService.AuthorizeAsync(user, resource, policy) after loading the data.
- A role is just a claim; everything ends up as a policy.