TExcelTAD
Home › ASP.NET Core › Authorization

Authorization

Once authentication has decided who the user is, authorization decides what they may do. ASP.NET Core uses a policy-based model: a policy is a named list of requirements, and an endpoint is allowed only when every requirement of its policy succeeds.

Requiring an authenticated user

The simplest rule is "any signed-in user". In minimal APIs you call RequireAuthorization(); in controllers you add [Authorize]:

csharp
builder.Services.AddAuthentication().AddJwtBearer();
builder.Services.AddAuthorization();

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/notes", () => new[] { "Buy milk" })
   .RequireAuthorization();

// A group: every endpoint inside needs a signed-in user...
var admin = app.MapGroup("/admin").RequireAuthorization("AdminOnly");
admin.MapGet("/stats", () => new { users = 12 });

// ...except ones that explicitly opt out.
admin.MapGet("/ping", () => "pong").AllowAnonymous();
csharp
[ApiController]
[Route("api/[controller]")]
[Authorize]                         // whole controller
public class OrdersController : ControllerBase
{
    [HttpGet]
    public IActionResult List() => Ok();

    [HttpDelete("{id}")]
    [Authorize(Roles = "admin")]    // stricter rule on one action
    public IActionResult Delete(int id) => NoContent();

    [HttpGet("public-count")]
    [AllowAnonymous]
    public int Count() => 3;
}

401 versus 403

The two "no" answers mean different things, and the framework picks the right one for you:

Status Name Meaning Produced by
401 Unauthorized "I don't know who you are" — no or invalid credentials the scheme's challenge
403 Forbidden "I know who you are, and the answer is no" the scheme's forbid
bash · try it yourself
$ curl -s -o /dev/null -w "%{http_code}\n" localhost:5000/admin/stats
$ curl -s -o /dev/null -w "%{http_code}\n" localhost:5000/admin/stats -H "Authorization: Bearer $EDITOR_TOKEN"
$ curl -s localhost:5000/admin/stats -H "Authorization: Bearer $ADMIN_TOKEN"
$ curl -s localhost:5000/admin/ping
401
403
{"users":12}
pong

Defining policies

Policies are registered with AddAuthorizationBuilder() (the fluent API added in .NET 7). Each policy combines requirements such as roles, claims or custom code:

csharp
builder.Services.AddAuthorizationBuilder()
    .AddPolicy("AdminOnly", p => p.RequireRole("admin"))
    .AddPolicy("Research", p => p
        .RequireAuthenticatedUser()
        .RequireClaim("department", "research", "lab"))
    .AddPolicy("Adult", p => p.RequireAssertion(ctx =>
        int.TryParse(ctx.User.FindFirst("age")?.Value, out var age) && age >= 18));

// Applies to endpoints with RequireAuthorization() but no named policy
builder.Services.AddAuthorizationBuilder()
    .SetFallbackPolicy(new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser().Build());
Requirement Builder method Passes when
Signed in RequireAuthenticatedUser() the identity is authenticated
Role RequireRole("admin", "owner") the user has any of the roles
Claim RequireClaim("dept", "a", "b") a dept claim has one of the values (any value if none listed)
User name RequireUserName("ada") the name claim matches
Custom RequireAssertion(ctx => …) your lambda returns true

Tip: A fallback policy protects every endpoint that has no authorization metadata at all — a safe "deny by default" setup. Mark public endpoints with AllowAnonymous().

How policy evaluation works

Under the hood, a policy is just a list of checks run against the ClaimsPrincipal. Here is a tiny re-implementation in plain C# using the real System.Security.Claims types:

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;

var policies = new Dictionary<string, List<Func<ClaimsPrincipal, bool>>>
{
    ["AdminOnly"] = new() { u => u.Identity?.IsAuthenticated == true, u => u.IsInRole("admin") },
    ["Research"] = new() { u => u.Identity?.IsAuthenticated == true,
                           u => u.HasClaim(c => c.Type == "department" && (c.Value == "research" || c.Value == "lab")) },
};

ClaimsPrincipal Make(string name, params (string Type, string Value)[] claims)
{
    var list = claims.Select(c => new Claim(c.Type, c.Value)).Append(new Claim(ClaimTypes.Name, name));
    return new ClaimsPrincipal(new ClaimsIdentity(list, "Bearer"));
}

var users = new[]
{
    Make("ada", (ClaimTypes.Role, "admin"), ("department", "research")),
    Make("ben", (ClaimTypes.Role, "editor"), ("department", "lab")),
    Make("cy", (ClaimTypes.Role, "editor"), ("department", "sales")),
    new ClaimsPrincipal(new ClaimsIdentity()), // anonymous
};

string Authorize(ClaimsPrincipal user, string policy)
{
    if (policies[policy].All(check => check(user))) return "200 OK";
    return user.Identity?.IsAuthenticated == true ? "403 Forbidden" : "401 Unauthorized";
}

foreach (var policy in new[] { "AdminOnly", "Research" })
    foreach (var u in users)
        Console.WriteLine(
quot;{policy,-9} {u.Identity?.Name ?? "(anon)",-6} -> {Authorize(u, policy)}");
AdminOnly ada    -> 200 OK
AdminOnly ben    -> 403 Forbidden
AdminOnly cy     -> 403 Forbidden
AdminOnly (anon) -> 401 Unauthorized
Research  ada    -> 200 OK
Research  ben    -> 200 OK
Research  cy     -> 403 Forbidden
Research  (anon) -> 401 Unauthorized

Notice the last decision: a failed policy turns into 401 for anonymous users and 403 for signed-in ones — the same rule the real authorization middleware follows.

Custom requirements and handlers

For logic that needs services (a database, the current time), write a requirement and a handler. The handler calls context.Succeed(requirement) when the check passes:

csharp
public record MinimumAgeRequirement(int Age) : IAuthorizationRequirement;

public class MinimumAgeHandler(TimeProvider clock)
    : AuthorizationHandler<MinimumAgeRequirement>
{
    protected override Task HandleRequirementAsync(
        AuthorizationHandlerContext context, MinimumAgeRequirement req)
    {
        var birth = context.User.FindFirst(ClaimTypes.DateOfBirth)?.Value;
        if (birth is not null &&
            DateOnly.Parse(birth).AddYears(req.Age) <= DateOnly.FromDateTime(clock.GetUtcNow().Date))
        {
            context.Succeed(req);
        }
        return Task.CompletedTask;
    }
}

builder.Services.AddSingleton<IAuthorizationHandler, MinimumAgeHandler>();
builder.Services.AddAuthorizationBuilder()
    .AddPolicy("Over18", p => p.AddRequirements(new MinimumAgeRequirement(18)));

Resource-based authorization

Sometimes the answer depends on the data: "only the author may edit this note". Policies on attributes cannot see the note, so you inject IAuthorizationService and check after loading it:

csharp
app.MapPut("/notes/{id:int}", async (int id, NoteDto dto, ClaimsPrincipal user,
    IAuthorizationService auth, NotesDb db) =>
{
    var note = await db.Notes.FindAsync(id);
    if (note is null) return Results.NotFound();

    var result = await auth.AuthorizeAsync(user, note, "IsAuthor");
    if (!result.Succeeded) return Results.Forbid();

    note.Text = dto.Text;
    await db.SaveChangesAsync();
    return Results.NoContent();
}).RequireAuthorization();

A resource-based check in miniature:

csharp · try it yourself
using System;
using System.Security.Claims;

var note = new Note(7, AuthorId: "42", "Draft plan");

bool IsAuthor(ClaimsPrincipal user, Note n) =>
    user.FindFirst(ClaimTypes.NameIdentifier)?.Value == n.AuthorId || user.IsInRole("admin");

ClaimsPrincipal User(string id, string role) => new(new ClaimsIdentity(new[]
{
    new Claim(ClaimTypes.NameIdentifier, id), new Claim(ClaimTypes.Role, role),
}, "Bearer"));

Console.WriteLine(
quot;Author 42 edits note 7: {IsAuthor(User("42", "user"), note)}"); Console.WriteLine(
quot;User 99 edits note 7: {IsAuthor(User("99", "user"), note)}"); Console.WriteLine(
quot;Admin 99 edits note 7: {IsAuthor(User("99", "admin"), note)}"); record Note(int Id, string AuthorId, string Text);
Author 42 edits note 7: True
User 99 edits note 7:   False
Admin 99 edits note 7:  True

Test yourself

A signed-in user without the admin role calls an AdminOnly endpoint. What status do they get?

  1. 401 Unauthorized
  2. 403 Forbidden
  3. 404 Not Found
  4. 302 redirect to /login

What does RequireRole("admin", "owner") require?

  1. Both roles
  2. Neither role
  3. At least one of the roles
  4. Exactly one role and no others

Which tool should you use for 'only the author may edit this note'?

  1. Resource-based authorization with IAuthorizationService.AuthorizeAsync(user, note, policy)
  2. [Authorize(Roles = "author")]
  3. A fallback policy
  4. CORS