# Lab 3: Customers and Baristas

**45 minutes** · Starts from `checkpoint-2` · Ends at `checkpoint-3`

You add real users, issue tokens, and lock down every endpoint so customers and staff can each do exactly what they should.

## Step 1: Identity with the EF Core store

Every command in this lab runs in `src/Roastery.Api`. Pin the versions so they match the rest of the project:

```bash
cd src/Roastery.Api
dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore --version 10.0.11
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer --version 10.0.11
dotnet add package System.IdentityModel.Tokens.Jwt --version 8.22.0
```

Create `Models/RoasteryUser.cs`:

```csharp
using Microsoft.AspNetCore.Identity;

namespace Roastery.Api.Models;

public class RoasteryUser : IdentityUser
{
    /// <summary>Links a login to a Customer row; null for staff.</summary>
    public int? CustomerId { get; set; }
}
```

Change `Data/RoasteryDbContext.cs` to inherit from `IdentityDbContext<RoasteryUser>`. Only the `using` and the base class change; keep the `base.OnModelCreating` call, because Identity configures its tables there:

```csharp
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Roastery.Api.Models;

namespace Roastery.Api.Data;

public class RoasteryDbContext(DbContextOptions<RoasteryDbContext> options)
    : IdentityDbContext<RoasteryUser>(options)
{
    // DbSets and OnModelCreating unchanged from Lab 2
}
```

Register Identity in `Program.cs`, after the exception handlers (add `using Microsoft.AspNetCore.Identity;` and `using Roastery.Api.Models;`):

```csharp
builder.Services.AddIdentityCore<RoasteryUser>(o => o.User.RequireUniqueEmail = true)
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<RoasteryDbContext>()
    .AddApiEndpoints();

// Identity's /login signs in through its own bearer-token scheme. Step 3 makes JWT the default.
builder.Services.AddAuthentication().AddBearerToken(IdentityConstants.BearerScheme);
```

Do not skip the `AddAuthentication` line. `AddIdentityCore().AddApiEndpoints()` registers a sign-in manager that needs authentication services, and in Development the app validates every registration at startup: without the line, both the migration below and `dotnet run` fail with `Some services are not able to be constructed (... ISecurityStampValidator ...)`.

Add the migration:

```bash
dotnet ef migrations add AddIdentity
```

You do not need `dotnet ef database update`: the Development startup block from Lab 2 already calls `db.Database.MigrateAsync()`, so the Identity tables appear the next time you run the app.

Now seed a `Staff` role and three users (passwords are in `src/README.md`): `barista@roastery.dev` in `Staff`, and `sam@example.com` and `jordan@example.com` linked to their customer rows. Create `Auth/IdentitySeed.cs`:

==- `Auth/IdentitySeed.cs`
```csharp
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Roastery.Api.Data;
using Roastery.Api.Models;

namespace Roastery.Api.Auth;

/// <summary>Creates the Staff role and the three workshop accounts.</summary>
public static class IdentitySeed
{
    public static async Task RunAsync(IServiceProvider services, CancellationToken ct = default)
    {
        var roles = services.GetRequiredService<RoleManager<IdentityRole>>();
        var users = services.GetRequiredService<UserManager<RoasteryUser>>();
        var db = services.GetRequiredService<RoasteryDbContext>();

        if (!await roles.RoleExistsAsync("Staff"))
            await roles.CreateAsync(new IdentityRole("Staff"));

        await EnsureUser(users, "barista@roastery.dev", "Barista1!", role: "Staff");

        var sam = await db.Customers.FirstOrDefaultAsync(c => c.Email == "sam@example.com", ct);
        var jordan = await db.Customers.FirstOrDefaultAsync(c => c.Email == "jordan@example.com", ct);
        await EnsureUser(users, "sam@example.com", "Customer1!", customerId: sam?.Id);
        await EnsureUser(users, "jordan@example.com", "Customer1!", customerId: jordan?.Id);
    }

    private static async Task EnsureUser(
        UserManager<RoasteryUser> users, string email, string password, string? role = null, int? customerId = null)
    {
        if (await users.FindByEmailAsync(email) is not null) return;

        var user = new RoasteryUser { UserName = email, Email = email, EmailConfirmed = true, CustomerId = customerId };
        var result = await users.CreateAsync(user, password);
        if (result.Succeeded && role is not null)
            await users.AddToRoleAsync(user, role);
    }
}
```
===

Call it right after the existing seed, inside the Development block (add `using Roastery.Api.Auth;`):

```csharp
await db.Database.MigrateAsync();
await Seed.RunAsync(db);
await IdentitySeed.RunAsync(scope.ServiceProvider);
```

It must run after `Seed.RunAsync`, because it looks up the customer rows to link Sam and Jordan.

Map Identity's endpoints under `/api/auth`. Put the group in a variable; you add our own token endpoint and the rate limit to the same group in later steps:

```csharp
var auth = app.MapGroup("/api/auth").WithTags("Auth");
auth.MapIdentityApi<RoasteryUser>();
```

Run the app and open Scalar: you now have `/api/auth/register`, `/login`, `/refresh`, `/manage/info`, and more.

Send the first request in `module-3.http`, `POST /api/auth/login`. It returns `200` with an opaque Identity token (`CfDJ8…`, not a three-part JWT). Copy it: in Step 6 you will see the locked-down endpoints reject it with `401`, because they only accept the JWTs from `POST /api/auth/token`, which you build next.

## Step 2: Issue a JWT with roles and customer id

Create `Options/JwtOptions.cs`:

```csharp
namespace Roastery.Api.Options;

public class JwtOptions
{
    public const string SectionName = "Jwt";
    public string Issuer { get; set; } = "roastery";
    public string Audience { get; set; } = "roastery";
    public string SigningKey { get; set; } = "";
    public int LifetimeMinutes { get; set; } = 60;
}
```

Add the non-secret settings to `appsettings.json`:

```json
"Jwt": {
  "Issuer": "roastery",
  "Audience": "roastery",
  "LifetimeMinutes": 60
}
```

Put the key in user secrets. Run these in `src/Roastery.Api`; `init` adds a `UserSecretsId` to the `.csproj`:

```bash
dotnet user-secrets init
dotnet user-secrets set "Jwt:SigningKey" "roastery-dev-signing-key-change-me-32-bytes"
```

!!! note Why the checkpoint also has a key in `appsettings.Development.json`
The committed `checkpoint-3` has a dev key under `Jwt:SigningKey` in `appsettings.Development.json`, marked DEV ONLY, so it runs straight after `git checkout` on a machine without your secrets. User secrets override it. Never put a real key in either file.
!!!

Bind the options in `Program.cs` (add `using Roastery.Api.Options;`). Put these two lines **above** the Step 1 `AddAuthentication` line: Step 3 replaces that line with a block that uses `jwt`, and C# will not let you use it before it is declared.

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

Create `Endpoints/AuthEndpoints.cs`. It holds the request and response records, a `MapTokenEndpoint` extension on the auth group, and the `IssueToken` handler from the concepts page. The response property must be `AccessToken`; the `.http` file reads `$.accessToken`.

==- `Endpoints/AuthEndpoints.cs`
```csharp
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Roastery.Api.Models;
using Roastery.Api.Options;

namespace Roastery.Api.Endpoints;

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

public static class AuthEndpoints
{
    public static RouteGroupBuilder MapTokenEndpoint(this RouteGroupBuilder group)
    {
        group.MapPost("/token", IssueToken).WithName("IssueToken")
             .WithSummary("Exchange credentials for a JWT carrying role and customer_id claims.");
        return group;
    }

    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()),
        };
        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));

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

Add it to the auth group (add `using Roastery.Api.Endpoints;` if it is not already there):

```csharp
var auth = app.MapGroup("/api/auth").WithTags("Auth");
auth.MapIdentityApi<RoasteryUser>();
auth.MapTokenEndpoint();
```

Restart and send the two `token` requests in the `.http` file, one per seed user. Each returns:

```json
{ "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9…", "tokenType": "Bearer" }
```

The file captures each token into a variable (`@customerToken`, `@staffToken`) that later requests use automatically. Paste one token into [jwt.io](https://jwt.io) and confirm the claims: Sam's token has `customer_id: "1"`; the barista's has the role claim (it appears under the long `http://schemas.microsoft.com/ws/2008/06/identity/claims/role` name) and no `customer_id`.

!!! warning If the captured token is empty
Some editors do not resolve `{{customerLogin.response.body.$.accessToken}}` (or lose it after a restart). If later requests return `401` and the variable looks empty, copy the `accessToken` value from the response and paste it directly: `@customerToken = eyJhbGci…`. Do the same for `@staffToken`.
!!!

## Step 3: Validate tokens and declare policies

Replace the Step 1 `builder.Services.AddAuthentication().AddBearerToken(...)` line with the `AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(...).AddBearerToken(IdentityConstants.BearerScheme)` block from the concepts page (it uses the `jwt` variable from Step 2). JWT is now the default scheme, and `/login` keeps working because its scheme is still registered. Then add the policies:

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

Put `OwnsOrderRequirement` and the `OwnsOrderHandler` from the concepts page in `Auth/OwnsOrder.cs` (namespace `Roastery.Api.Auth`; `using System.Security.Claims;`, `using Microsoft.AspNetCore.Authorization;`, `using Roastery.Api.Models;`). The requirement is a one-liner: `public class OwnsOrderRequirement : IAuthorizationRequirement;`.

`Program.cs` now needs these usings at the top:

```csharp
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
```

Then add the two `Use` calls. Step 5 adds the rest of the pipeline, so the full order is shown there.

```csharp
app.UseAuthentication();
app.UseAuthorization();
```

## Step 4: Lock it down

Restructure `ProductEndpoints` into two groups that share a prefix. Keep the timing filter and the endpoint names from Lab 2: `CreateProduct` returns `CreatedAtRoute(..., "GetProduct", ...)`, which fails if `GetProduct` loses its name.

```csharp
public static IEndpointRouteBuilder MapProductEndpoints(this IEndpointRouteBuilder app)
{
    var products = app.MapGroup("/api/products").WithTags("Products");
    products.AddEndpointFilter(TimingFilter); // the Lab 2 filter, moved into a static method

    products.MapGet("/", GetProducts).WithName("GetProducts")
            .WithSummary("List products, optionally filtered by roast and stock.");
    products.MapGet("/{id:int}", GetProduct).WithName("GetProduct");

    // Staff-only writes. Any endpoint added to this sub-group later is protected by default.
    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");

    return app;
}
```

`UpdateProduct` and `DeleteProduct` are new. They need two more methods on the catalog:

==- Update and delete: handlers and catalog methods
Add to `Services/IProductCatalog.cs`:

```csharp
Task<Product?> UpdateAsync(int id, CreateProductRequest request, CancellationToken ct);
Task<bool> RemoveAsync(int id, CancellationToken ct);
```

Implement them in `Services/EfProductCatalog.cs`. These load a *tracked* entity (no `AsNoTracking`) so `SaveChangesAsync` sees the change:

```csharp
public async Task<Product?> UpdateAsync(int id, CreateProductRequest request, CancellationToken ct)
{
    var product = await db.Products.FirstOrDefaultAsync(p => p.Id == id, ct);
    if (product is null) return null;

    product.Name = request.Name;
    product.Roast = Enum.Parse<Roast>(request.Roast, true);
    product.Price = request.Price;
    product.StockQuantity = request.StockQuantity;
    await db.SaveChangesAsync(ct);
    return product;
}

public async Task<bool> RemoveAsync(int id, CancellationToken ct)
{
    var product = await db.Products.FirstOrDefaultAsync(p => p.Id == id, ct);
    if (product is null) return false;
    db.Products.Remove(product);
    await db.SaveChangesAsync(ct);
    return true;
}
```

Add the handlers to `Endpoints/ProductEndpoints.cs`:

```csharp
static async Task<Results<Ok<ProductDto>, NotFound>> UpdateProduct(
    int id, CreateProductRequest request, IProductCatalog catalog, CancellationToken ct)
{
    var updated = await catalog.UpdateAsync(id, request, ct);
    return updated is null ? TypedResults.NotFound() : TypedResults.Ok(updated.ToDto());
}

static async Task<Results<NoContent, NotFound>> DeleteProduct(
    int id, IProductCatalog catalog, CancellationToken ct)
{
    var removed = await catalog.RemoveAsync(id, ct);
    return removed ? TypedResults.NoContent() : TypedResults.NotFound();
}
```

And the Lab 2 inline filter becomes a named method in the same class:

```csharp
static async ValueTask<object?> TimingFilter(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
{
    var sw = Stopwatch.StartNew();
    var result = await next(context);
    context.HttpContext.Response.Headers["X-Elapsed-Ms"] = sw.ElapsedMilliseconds.ToString();
    return result;
}
```
===

Replace `Endpoints/OrderEndpoints.cs` with the version below. Read it rather than retyping it; the changes from Lab 2 are:

- The whole group gets `.RequireAuthorization()` (any authenticated user).
- `PUT /{id}/status` additionally gets `.RequireAuthorization("Staff")`.
- `ListOrders` and `CreateOrder` take a `ClaimsPrincipal user` parameter. `CreateOrder` reads `customer_id` from it instead of the hard-coded `CustomerId = 1`, and returns `403` (`ForbidHttpResult` joins its return type) when the claim is missing.
- `GetOrder` uses `IAuthorizationService` with the `OwnsOrder` policy, and answers `404` rather than `403` for someone else's order.
- `ListOrders` filters to the caller's own orders unless the caller is `Staff`, and returns an empty page when there is no `customer_id` at all.

==- `Endpoints/OrderEndpoints.cs`
```csharp
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;
using Roastery.Api.Contracts;
using Roastery.Api.Data;
using Roastery.Api.Domain;
using Roastery.Api.Models;

namespace Roastery.Api.Endpoints;

public static class OrderEndpoints
{
    public static IEndpointRouteBuilder MapOrderEndpoints(this IEndpointRouteBuilder app)
    {
        // The whole group requires an authenticated caller.
        var group = app.MapGroup("/api/orders").WithTags("Orders").RequireAuthorization();

        group.MapGet("/", ListOrders).WithName("ListOrders").WithSummary("List orders, paged.");
        group.MapGet("/{id:int}", GetOrder).WithName("GetOrder");
        group.MapPost("/", CreateOrder).WithName("CreateOrder").WithSummary("Place an order.");

        // Advancing an order's status is staff-only.
        group.MapPut("/{id:int}/status", ChangeStatus).WithName("ChangeOrderStatus")
             .RequireAuthorization("Staff")
             .WithSummary("Advance an order through its lifecycle (staff only).");

        return app;
    }

    static async Task<Ok<PagedResult<OrderSummaryDto>>> ListOrders(
        [AsParameters] OrderQuery query, ClaimsPrincipal user, RoasteryDbContext db, CancellationToken ct)
    {
        var page = Math.Max(1, query.Page);
        var pageSize = Math.Clamp(query.PageSize, 1, 100);
        OrderStatus? status = Enum.TryParse<OrderStatus>(query.Status, true, out var s) ? s : null;

        var orders = db.Orders.AsNoTracking()
            .Where(o => status == null || o.Status == status);

        // Customers see only their own orders; staff see everything.
        if (!user.IsInRole("Staff"))
        {
            // Fail closed: an account with no customer record (e.g. fresh from /register) sees nothing, not everything.
            if (!int.TryParse(user.FindFirstValue("customer_id"), out var cid))
                return TypedResults.Ok(new PagedResult<OrderSummaryDto>([], page, pageSize, 0));
            orders = orders.Where(o => o.CustomerId == cid);
        }

        var ordered = orders.OrderByDescending(o => o.PlacedAt);
        var total = await ordered.CountAsync(ct);
        var items = await ordered
            .Skip((page - 1) * pageSize).Take(pageSize)
            .Select(o => new OrderSummaryDto(o.Id, o.CustomerId, o.Status.ToString(), o.Total, o.PlacedAt))
            .ToListAsync(ct);

        return TypedResults.Ok(new PagedResult<OrderSummaryDto>(items, page, pageSize, total));
    }

    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");
        // A customer asking for someone else's order gets 404, not 403: a 403 would confirm it exists.
        return result.Succeeded ? TypedResults.Ok(order.ToDto()) : TypedResults.NotFound();
    }

    static async Task<Results<CreatedAtRoute<OrderDto>, ValidationProblem, ForbidHttpResult>> CreateOrder(
        CreateOrderRequest request, ClaimsPrincipal user, RoasteryDbContext db, TimeProvider clock, CancellationToken ct)
    {
        // Identity comes from the token, never the request body (OWASP API1). No customer record, no orders.
        if (!int.TryParse(user.FindFirstValue("customer_id"), out var customerId))
            return TypedResults.Forbid();

        var ids = request.Lines.Select(l => l.ProductId).ToList();
        var products = await db.Products.Where(p => ids.Contains(p.Id)).ToDictionaryAsync(p => p.Id, ct);

        var errors = new Dictionary<string, string[]>();
        foreach (var (line, i) in request.Lines.Select((l, i) => (l, i)))
        {
            if (!products.TryGetValue(line.ProductId, out var product))
                errors[$"Lines[{i}].ProductId"] = ["Unknown product."];
            else if (product.StockQuantity < line.Quantity)
                errors[$"Lines[{i}].Quantity"] = [$"Only {product.StockQuantity} in stock."];
        }
        if (errors.Count > 0) return TypedResults.ValidationProblem(errors);

        var order = new Order
        {
            CustomerId = customerId,
            PlacedAt = clock.GetUtcNow(),
            Lines = request.Lines.Select(l => new OrderLine
            {
                ProductId = l.ProductId, Quantity = l.Quantity, UnitPrice = products[l.ProductId].Price
            }).ToList()
        };
        order.Total = order.Lines.Sum(l => l.Quantity * l.UnitPrice);
        foreach (var line in order.Lines) products[line.ProductId].StockQuantity -= line.Quantity;

        db.Orders.Add(order);
        await db.SaveChangesAsync(ct);
        return TypedResults.CreatedAtRoute(order.ToDto(), "GetOrder", new { id = order.Id });
    }

    static async Task<Results<Ok<OrderDto>, NotFound, ValidationProblem>> ChangeStatus(
        int id, ChangeOrderStatusRequest request, RoasteryDbContext db, CancellationToken ct)
    {
        if (!Enum.TryParse<OrderStatus>(request.Status, true, out var target))
            return TypedResults.ValidationProblem(new Dictionary<string, string[]>
            {
                [nameof(request.Status)] = [$"Unknown status '{request.Status}'."]
            });

        var order = await db.Orders.Include(o => o.Lines).FirstOrDefaultAsync(o => o.Id == id, ct);
        if (order is null) return TypedResults.NotFound();

        if (!OrderLifecycle.CanTransition(order.Status, target))
            throw new InvalidOrderTransitionException(order.Status, target);

        order.Status = target;
        await db.SaveChangesAsync(ct);
        return TypedResults.Ok(order.ToDto());
    }
}
```
===

The inner `if` is the important part. The tempting one-liner, `if (!IsInRole("Staff") && int.TryParse(...)) filter`, skips the filter when the claim is missing and shows that caller **every** order. Step 6 proves the difference.

## Step 5: Rate limiting, CORS, and headers

Add the `AddRateLimiter` configuration from the concepts page (`using System.Threading.RateLimiting;` and `using Microsoft.AspNetCore.RateLimiting;`) and put the `"auth"` limit on the auth group, so the group reads:

```csharp
var auth = app.MapGroup("/api/auth").WithTags("Auth").RequireRateLimiting("auth");
auth.MapIdentityApi<RoasteryUser>();
auth.MapTokenEndpoint();
```

Add CORS with a named policy that allows only `https://localhost:5173` (the address of the workshop's small demo front end):

```csharp
const string FrontendCors = "Frontend";
builder.Services.AddCors(options => options.AddPolicy(FrontendCors, policy =>
    policy.WithOrigins("https://localhost:5173").AllowAnyHeader().AllowAnyMethod()));
```

Add `Auth/SecurityHeadersMiddleware.cs`, an extension method so `Program.cs` stays readable:

```csharp
namespace Roastery.Api.Auth;

public static class SecurityHeadersMiddleware
{
    public static IApplicationBuilder UseSecurityHeaders(this IApplicationBuilder app) =>
        app.Use(async (context, next) =>
        {
            var headers = context.Response.Headers;
            headers["X-Content-Type-Options"] = "nosniff";
            headers["Referrer-Policy"] = "no-referrer";
            headers["X-Frame-Options"] = "DENY";
            await next();
        });
}
```

To drop the `Server: Kestrel` header, turn it off on Kestrel itself, next to the other `builder` calls:

```csharp
builder.WebHost.ConfigureKestrel(o => o.AddServerHeader = false);
```

!!! warning Why not `Headers.Remove("Server")`?
Removing the header in the middleware has no effect: Kestrel writes the `Server` header when the response starts, after middleware runs, so the response still carries `Server: Kestrel`. `AddServerHeader = false` is the switch that works, and it is what the checkpoint uses.
!!!

The finished pipeline, in this order (from the checkpoint's `Program.cs`):

```csharp
app.UseExceptionHandler();
app.UseStatusCodePages();
app.UseHttpsRedirection();
if (!app.Environment.IsDevelopment()) app.UseHsts();
app.UseSecurityHeaders();
app.UseRateLimiter();
app.UseCors(FrontendCors);
app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/health", () => "Healthy").ExcludeFromDescription();
app.MapProductEndpoints();
app.MapOrderEndpoints();

var auth = app.MapGroup("/api/auth").WithTags("Auth").RequireRateLimiting("auth");
auth.MapIdentityApi<RoasteryUser>();
auth.MapTokenEndpoint();

app.MapOpenApi();
app.MapScalarApiReference();
```

Because `UseRateLimiter` runs before `UseAuthentication`, there is no signed-in user yet when the global limiter runs, so it partitions by client IP address (the concepts page code reads `RemoteIpAddress` for exactly that reason). That is a reasonable choice: it rejects a flood of requests with bad tokens before any token is validated. To partition by user instead, move `UseRateLimiter()` after `UseAuthentication()` and key on `context.User.Identity?.Name`, falling back to the IP for anonymous callers.

## Step 6: Prove it

Send the verification block in `module-3.http`. Every request has its expected status in a comment:

| Request | Expected |
|---|---|
| `GET /api/products` with no token | `200` |
| `POST /api/products` with no token | `401` |
| `POST /api/products` with `@customerToken` | `403` |
| `POST /api/products` with `@staffToken` | `201` |
| `GET /api/orders` with `@identityToken`, the token from Identity's `/login` | `401`: our endpoints accept only our JWTs |
| `POST /api/orders` with `@customerToken`, body carries no customer id | `201`, and the order belongs to Sam (`customerId: 1`) |
| `GET /api/orders/{that order's id}` with `@customerToken` | `200` |
| `GET /api/orders/2` (Jordan's order) with `@customerToken` | `404` |
| Same request with `@staffToken` | `200` |
| `PUT /api/orders/{id}/status` with `@customerToken` | `403` |
| Same request with `@staffToken` | `200` |
| The last request, `POST /api/auth/token` with a wrong password, sent several times fast | `401`, then `429` once the window's limit is hit |

The `"auth"` limiter is a single fixed window of 5 requests a minute shared by **every** `/api/auth/*` call from every caller. The first three requests in the file (Identity's `/login` and the two token captures) already used three of those permits, so you may see `429` after only two wrong-password attempts. Wait a minute before the "fail closed" box below; its register and token requests share the same window. If a token capture itself gets `429`, wait a minute and resend it.

!!! Discuss with your neighbor
Why `404` rather than `403` for another customer's order? Would you make the same choice for `PUT /api/orders/{id}/status`? There is a reasonable argument each way; be ready to say which you picked and why.
!!!

!!! Optional: fail closed (about 5 minutes; skip it if you are behind)
The "Optional: fail closed" block at the bottom of `module-3.http` registers `eve@example.com`, gets her a token, and calls the order endpoints. Eve has no role and no `customer_id` claim:

| Request as Eve | Expected |
|---|---|
| `GET /api/orders` | `200` with `"items": []` and `"totalCount": 0` |
| `POST /api/orders` | `403` |
| `GET /api/orders/1` | `404` |

Now swap the customer filter in `ListOrders` for the tempting one-liner and send the list request again:

```csharp
if (!user.IsInRole("Staff") && int.TryParse(user.FindFirstValue("customer_id"), out var cid))
    orders = orders.Where(o => o.CustomerId == cid);
```

Eve now sees **every customer's orders**. That is OWASP API1, and it is why authorization code fails closed. **Put the fail-closed version back before you commit.** Would you rather return an empty page or a `403` for the list? An alternative is a `Customer` policy (`p.RequireClaim("customer_id")`) on the order endpoints that customers use.
!!!

## Stretch goals

- Add refresh tokens to `/api/auth/token`: return a `refreshToken` alongside `accessToken`, store it against the user, and add `POST /api/auth/token/refresh`. Set `Jwt:LifetimeMinutes` to `2` to test it. (Identity's own `/api/auth/refresh` works, but it refreshes Identity's opaque tokens, not our JWTs.)
- Add an `ApiKey` authentication scheme for a partner integration (a header, a lookup in configuration) and show that a single endpoint can accept either scheme with `.RequireAuthorization(p => p.AddAuthenticationSchemes("Bearer", "ApiKey").RequireAuthenticatedUser())`.
- Replace `RequireRole("Staff")` with a claims-based `permission` scheme (`orders:write`, `products:write`) and issue the claims in the token.

## Common pitfalls

- **Everything returns 401 even with a token.** `UseAuthorization` is before `UseAuthentication`, or the `Use` calls come after the `Map` calls.
- **`IDX10653: The encryption algorithm … key size`.** The signing key is shorter than 32 bytes.
- **The app or `dotnet ef` fails with "Some services are not able to be constructed".** The Step 1 `AddAuthentication()` line is missing.
- **`/api/auth/login` returns 500.** The `.AddBearerToken(IdentityConstants.BearerScheme)` call is missing (you dropped it when you replaced the Step 1 line in Step 3). `AddIdentityCore` does not register Identity's bearer scheme for you.
- **The `/login` token gets `401` everywhere.** Expected: the endpoints accept only our JWTs. Use `/api/auth/token`.
- **`user-secrets` says it cannot find a project.** Run it in `src/Roastery.Api`, not the repo root.
- **`CreatedAtRoute` throws "No route matches the supplied values".** `GetProduct` lost its `.WithName("GetProduct")` in the restructure.
- **Sudden `429` on a token request.** The `"auth"` window is shared by every `/api/auth/*` call; wait a minute.
- **Some staff endpoints are open.** You applied `RequireAuthorization` to individual endpoints and missed one. Apply it to the group.
- **Orders belong to the wrong customer.** A `customerId` is still being read from the request body.

## Checkpoint

```bash
git add -A && git commit -m "Lab 3 complete"
# or: git checkout checkpoint-3
```

Next: [Module 4: Performance, Resilience, and Testing](../module-4-production/concepts.md)
