# Module 3: Identity, Tokens, and Authorization

**1:00 – 2:15 PM** · Concepts 25 min · [Lab](lab.md) 45 min

[▶ **Present this module**](../slides/module-3.html)

## Learning objectives

By the end of this module you can add ASP.NET Core Identity with token endpoints, protect endpoints with JWT bearer authentication, express permissions as policies rather than role checks scattered through code, and harden the API against the most common attacks.

## Authentication and authorization are different questions

*Authentication* answers "who is this?" and produces a `ClaimsPrincipal`. *Authorization* answers "may they do this?" and produces allow or deny. They are separate middleware, and the order is not negotiable:

```csharp
app.UseAuthentication();   // populates HttpContext.User
app.UseAuthorization();    // evaluates policies against it
app.MapProductEndpoints(); // endpoints come after both
```

Anything that needs to know *who* the caller is must run after `UseAuthentication`. Keep that in mind when you get to rate limiting below.

```mermaid
flowchart LR
    Req[Request + Bearer token] --> A[UseAuthentication\nvalidate JWT → ClaimsPrincipal]
    A --> Z[UseAuthorization\nevaluate policy]
    Z -->|allowed| H[Handler]
    Z -->|no principal| U[401 Unauthorized]
    Z -->|principal, policy fails| F[403 Forbidden]
```

## Two ways to get a token

**`MapIdentityApi<TUser>()`** gives you register, login, refresh, confirm-email, password-reset, and account-management endpoints for free. It is a superb starting point for account management.

Its `/login` endpoint, however, signs in through Identity's own bearer-token scheme (`Identity.Bearer`), and the token it returns is an opaque, data-protected string, not a JWT. The all-in-one `AddIdentityApiEndpoints<TUser>()` registers that scheme for you. Roastery uses the leaner `AddIdentityCore<TUser>().AddApiEndpoints()`, which registers what the endpoints need (sign-in manager, token providers, a no-op email sender) but **not** the scheme. Without it, `/login` fails with `500` and "No sign-in authentication handlers are registered… Identity.Bearer". So we register it ourselves with one call, `.AddBearerToken(IdentityConstants.BearerScheme)`, next to JWT bearer (shown below). The two setup methods look interchangeable and are not.

JWT bearer stays the **default** scheme, so the endpoints only accept our JWTs. An Identity token from `/login` gets `401` from `/api/orders`: it carries none of our claims, and nothing is configured to read it.

**Issuing your own JWT** gives you control over the claims. Roastery needs a `customer_id` claim and a `role` claim so that authorization can work without a database round-trip on every request.

So we use both: Identity's endpoints for account management (`/register` and friends), and a small `POST /api/auth/token` that checks the password with `UserManager.CheckPasswordAsync` and issues a JWT. That is the only place Roastery tokens come from.

```csharp
public record TokenRequest(string Email, string Password);
public record TokenResponse(string AccessToken, string TokenType = "Bearer");
```

```csharp
static async Task<Results<Ok<TokenResponse>, UnauthorizedHttpResult>> IssueToken(
    TokenRequest request, UserManager<RoasteryUser> users, IOptions<JwtOptions> jwtOptions)
{
    var user = await users.FindByEmailAsync(request.Email);
    if (user is null || !await users.CheckPasswordAsync(user, request.Password))
        return TypedResults.Unauthorized();

    var jwt = jwtOptions.Value;
    var roles = await users.GetRolesAsync(user);

    var claims = new List<Claim>
    {
        new(JwtRegisteredClaimNames.Sub, user.Id),
        new(JwtRegisteredClaimNames.Email, user.Email!),
        new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
    };
    // Staff have no customer row, so they get no customer_id claim.
    if (user.CustomerId is int cid) claims.Add(new Claim("customer_id", cid.ToString()));
    claims.AddRange(roles.Select(r => new Claim(ClaimTypes.Role, r)));

    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.SigningKey));
    var token = new JwtSecurityToken(
        issuer: jwt.Issuer, audience: jwt.Audience, claims: claims,
        expires: DateTime.UtcNow.AddMinutes(jwt.LifetimeMinutes),
        signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));

    return TypedResults.Ok(new TokenResponse(new JwtSecurityTokenHandler().WriteToken(token)));
}
```

The JSON property is `accessToken` (camelCase of `AccessToken`). The `.http` file captures it by that name, so do not rename it.

!!! warning No lockout here
`CheckPasswordAsync` only compares the password; it never counts failures or locks the account. The rate limiter below is our brute-force defense. In production prefer `SignInManager.CheckPasswordSignInAsync(user, password, lockoutOnFailure: true)`, which honors Identity's lockout settings. It needs `AddSignInManager()` on the Identity builder.
!!!

## Validating the token

```csharp
builder.Services.Configure<JwtOptions>(builder.Configuration.GetSection(JwtOptions.SectionName));
var jwt = builder.Configuration.GetSection(JwtOptions.SectionName).Get<JwtOptions>() ?? new JwtOptions();

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateIssuerSigningKey = true,
            ValidateLifetime = true,
            ValidIssuer = jwt.Issuer,
            ValidAudience = jwt.Audience,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.SigningKey)),
            ClockSkew = TimeSpan.FromSeconds(30),
        };
    })
    // Lets MapIdentityApi's /login and /refresh work. JWT stays the default scheme.
    .AddBearerToken(IdentityConstants.BearerScheme);
```

The signing key never lives in `appsettings.json`. In development, use user secrets (run this in `src/Roastery.Api`, the project folder):

```bash
dotnet user-secrets set "Jwt:SigningKey" "a-development-key-that-is-at-least-32-bytes-long!"
```

User secrets override `appsettings.Development.json`. The checkpoint also carries a clearly labelled dev-only key in `appsettings.Development.json` so it runs straight after `git checkout`; that file is never deployed.

In production it comes from an environment variable or a key vault, which is exactly how Module 5 passes it into the container.

!!! warning
HS256 requires a key of at least 256 bits (32 bytes). A shorter key throws at token creation with a message that is easy to misread as a configuration typo.
!!!

## Authorization as policy

Scattering `if (user.IsInRole("Staff"))` through handlers is how permission bugs are born. Declare the rules once as named policies and apply them to groups. Here the public reads and the staff-only writes share one prefix, so the writes live in a sub-group:

```csharp
builder.Services.AddAuthorizationBuilder()
    .AddPolicy("Staff", p => p.RequireRole("Staff"))
    .AddPolicy("OwnsOrder", p => p.AddRequirements(new OwnsOrderRequirement()));
```

```csharp
var products = app.MapGroup("/api/products").WithTags("Products");
products.MapGet("/", GetProducts).WithName("GetProducts");
products.MapGet("/{id:int}", GetProduct).WithName("GetProduct");

var staff = products.MapGroup("/").RequireAuthorization("Staff");
staff.MapPost("/", CreateProduct).WithName("CreateProduct");
staff.MapPut("/{id:int}", UpdateProduct).WithName("UpdateProduct");
staff.MapDelete("/{id:int}", DeleteProduct).WithName("DeleteProduct");
```

Applying the policy to the group means a new endpoint added tomorrow is protected by default. Applying it endpoint by endpoint means a new endpoint is open by default. Choose the default that fails safe.

## Resource-based authorization

"A customer may see only their own orders" is not a role check; it depends on the order. That is an `IAuthorizationHandler` that receives the resource:

```csharp
public class OwnsOrderHandler : AuthorizationHandler<OwnsOrderRequirement, Order>
{
    protected override Task HandleRequirementAsync(
        AuthorizationHandlerContext context, OwnsOrderRequirement requirement, Order order)
    {
        if (context.User.IsInRole("Staff") ||
            context.User.FindFirstValue("customer_id") == order.CustomerId.ToString())
            context.Succeed(requirement);
        return Task.CompletedTask;
    }
}
```

```csharp
static async Task<Results<Ok<OrderDto>, NotFound>> GetOrder(
    int id, ClaimsPrincipal user, RoasteryDbContext db, IAuthorizationService auth, CancellationToken ct)
{
    var order = await db.Orders.AsNoTracking().Include(o => o.Lines).FirstOrDefaultAsync(o => o.Id == id, ct);
    if (order is null) return TypedResults.NotFound();

    var result = await auth.AuthorizeAsync(user, order, "OwnsOrder");
    return result.Succeeded ? TypedResults.Ok(order.ToDto()) : TypedResults.NotFound();
}
```

Notice the last line returns `NotFound`, not `Forbid`, when a customer asks for someone else's order. A `403` confirms the order exists; a `404` reveals nothing. The lab asks you to decide which is right for each endpoint.

## Never trust the body for identity

In Lab 2, `CreateOrder` hard-coded `CustomerId = 1`. The fix is not to accept it from the request; it is to read it from the token:

```csharp
// No customer record, no orders: fail closed with 403 rather than throwing.
if (!int.TryParse(user.FindFirstValue("customer_id"), out var customerId))
    return TypedResults.Forbid();
```

`Forbid()` adds `ForbidHttpResult` to the handler's return type: `Results<CreatedAtRoute<OrderDto>, ValidationProblem, ForbidHttpResult>`.

A request body that carries `customerId` is an invitation to place orders as someone else. This is OWASP API1, Broken Object Level Authorization, and it is the most common API vulnerability in the wild.

The other half of API1 is deciding what happens when the claim is *missing*. Anyone can call `/api/auth/register`, and a self-registered user has no role and no `customer_id`. Code that says "filter to the caller's orders *if* they have a `customer_id`" quietly shows that user everything. Authorization code should fail closed: no claim, no data. In Roastery, a non-staff caller without a `customer_id` gets an empty order list and a `403` from `POST /api/orders`.

## Hardening quick hits

Each of these is a few lines. The lab adds all of them.

| Concern | What you add | Why |
|---|---|---|
| Brute force on login | `AddRateLimiter` with a fixed window on `/api/auth/*` | A handful of attempts a minute is plenty for a human and useless for a script |
| Abuse elsewhere | A global sliding-window limiter partitioned by client IP (or user, if it runs after authentication) | Protects the database from any single caller |
| Cross-origin calls | `AddCors` with an explicit origin list | `AllowAnyOrigin` with credentials is a vulnerability, not a convenience |
| Transport | `UseHttpsRedirection` and `UseHsts` outside development | Tokens in transit are only as safe as the transport |
| Response headers | A small middleware that sets `X-Content-Type-Options`, `Referrer-Policy`, `X-Frame-Options`; `AddServerHeader = false` on Kestrel | Cheap defense in depth |

```csharp
builder.Services.AddRateLimiter(options =>
{
    options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
    options.AddFixedWindowLimiter("auth", o =>
    {
        o.Window = TimeSpan.FromMinutes(1);
        o.PermitLimit = 5;
        o.QueueLimit = 0;
    });
    // UseRateLimiter runs before UseAuthentication, so there is no user yet: partition by client IP.
    options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(context =>
        RateLimitPartition.GetSlidingWindowLimiter(
            context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
            _ => new SlidingWindowRateLimiterOptions
            {
                Window = TimeSpan.FromSeconds(10), PermitLimit = 100, SegmentsPerWindow = 5, QueueLimit = 0
            }));
});
// …
app.UseRateLimiter();
var auth = app.MapGroup("/api/auth").WithTags("Auth").RequireRateLimiting("auth");
```

Two things about this configuration are worth saying out loud:

- **The `"auth"` limiter is one bucket.** `AddFixedWindowLimiter` is not partitioned, so every request to every `/api/auth/*` endpoint, from every caller, shares the same 5 permits a minute. That is fine for a workshop and too blunt for production, where you would partition by IP (and by the email being attempted) with `AddPolicy` and `RateLimitPartition.GetFixedWindowLimiter`.
- **The global limiter partitions by IP, not by user.** `UseRateLimiter` runs before `UseAuthentication`, so `context.User` is still anonymous when the limiter runs; reading the user name there would always fall through to the IP anyway. To partition authenticated callers by user, move `UseRateLimiter()` after `UseAuthentication()` and key on `context.User.Identity?.Name`.

!!! warning Removing the `Server` header
`context.Response.Headers.Remove("Server")` in middleware does nothing useful: Kestrel adds `Server: Kestrel` when the response starts, after your middleware has run. The right switch is on Kestrel itself, and it is what the checkpoint uses: `builder.WebHost.ConfigureKestrel(o => o.AddServerHeader = false);`.
!!!

## The OWASP API Top 10 in five minutes

| # | Risk | Where Roastery addresses it |
|---|---|---|
| API1 | Broken object level authorization | `OwnsOrder` handler; `customer_id` from the token; failing closed when the claim is missing (a lab exercise) |
| API2 | Broken authentication | Identity + JWT with expiry, issuer, and audience checks |
| API3 | Broken object property level authorization | DTOs; the client cannot set `Total` or `Status` |
| API4 | Unrestricted resource consumption | Rate limiting; clamped `pageSize` |
| API5 | Broken function level authorization | `Staff` policy on the group |
| API8 | Security misconfiguration | Explicit CORS, HSTS, secure headers, `AddServerHeader = false` |
| API9 | Improper inventory management | OpenAPI document, versioning in Module 5 |

## Head to the lab

[Lab 3: Customers and Baristas](lab.md)
