Project: auth, tests and deploy
Part two of the capstone makes the Order management API production-ready: JWT login with identity taken from the token, owner checks and an admin policy, unit and integration tests, a multi-stage Docker image with a migrations bundle, and a CI pipeline.
74.1 The bug: anyone can order as Amit
- The request DTO takes Email from the body and there is no login.
- Anyone can send Amit's email and the order is created in his name (201).
- The orders list is visible to everyone, and anyone can set a product price to 1 rupee.
public record CreateOrderRequest( [Required, EmailAddress] string Email, [Required, MinLength(1), MaxLength(20)] List<OrderLine> Items);$ curl -i localhost:5074/api/orders \ -H "Content-Type: application/json" \ -d '{"email":"amit@example.com", "items":[{"productId":1,"quantity":2}]}'HTTP/1.1 201 CreatedLocation: /api/orders/1{ "id": 1, "email": "amit@example.com", "status": "Placed", "total": 4998.0, ... } $ curl -i localhost:5074/api/ordersHTTP/1.1 200 OK[{ "id": 1, "email": "amit@example.com", "status": "Placed", "total": 4998.0, ... }] $ curl -i -X PUT localhost:5074/api/products/1 \ -H "Content-Type: application/json" \ -d '{"name":"Mixer Grinder","price":1,"stock":5}'HTTP/1.1 204 No Content- Step 1
1.No identity: the API does not know who is calling
- Step 2
2.Email comes from the body: whatever the client says
- Step 3
3.No roles: everyone can do admin work
- Step 4
4.Fix: authentication (who are you?) + authorization (what can you do?)
74.2 Authentication vs authorization
| Point | Authentication | Authorization |
|---|---|---|
| Question | Who are you? | What are you allowed to do? |
| Here | JwtBearer validates the token | Policy (admin role) + owner check |
| Failure status | 401 Unauthorized | 403 Forbidden (or 404 to hide existence) |
74.3 JWT authentication setup
- MapInboundClaims = false keeps short claim names like sub and role as they are.
- TokenValidationParameters verify issuer, audience and signing key.
- The admin policy requires the claim role = admin.
builder.Services.AddAuthentication() .AddJwtBearer(o => { o.MapInboundClaims = false; o.TokenValidationParameters = new() { ValidIssuer = jwt["Issuer"], ValidAudience = jwt["Audience"], IssuerSigningKey = key }; });builder.Services.AddAuthorizationBuilder() .AddPolicy("admin", p => p.RequireClaim("role", "admin"));74.4 TokenService: demo login
- A small TokenService issues the token for a demo login endpoint; in a real project Identity does this.
- The sub claim carries the email, the role claim carries the role.
- Token lasts 30 minutes (expiresIn 1800), signed with HMAC-SHA256; a wrong password gives 401.
var descriptor = new SecurityTokenDescriptor{ Issuer = jwt["Issuer"], Audience = jwt["Audience"], Subject = new ClaimsIdentity([ new Claim("sub", user.Email), new Claim("role", user.Role)]), Expires = time.GetUtcNow() .AddMinutes(30).UtcDateTime, SigningCredentials = new(key, SecurityAlgorithms.HmacSha256)};return handler.CreateToken(descriptor);$ curl -i localhost:5074/api/auth/token \ -H "Content-Type: application/json" \ -d '{"email":"amit@example.com", "password":"Amit@1234"}'HTTP/1.1 200 OK{"accessToken":"eyJhbGciOiJIUzI1NiIs...", "expiresIn":1800} $ curl -i localhost:5074/api/auth/token \ -H "Content-Type: application/json" \ -d '{"email":"amit@example.com", "password":"wrong"}'HTTP/1.1 401 UnauthorizedContent-Type: application/problem+json74.5 Orders: email from the token
- RequireAuthorization() on the orders group: no token -> 401.
- Place takes a ClaimsPrincipal and reads the email from the sub claim.
- Even if Ravi puts Amit's email in the body, the order is created as ravi@example.com.
var g = app.MapGroup("/api/orders") .WithTags("Orders") .RequireAuthorization(); static async Task<Results<Created<OrderDto>, ValidationProblem>> Place( CreateOrderRequest request, ClaimsPrincipal user, OrderService orders){ var email = user.Email(); var result = await orders .PlaceAsync(email, request);$ curl -i localhost:5074/api/orders \ -H "Content-Type: application/json" \ -d '{"items":[{"productId":1,"quantity":2}]}'HTTP/1.1 401 UnauthorizedWWW-Authenticate: Bearer $ curl -i localhost:5074/api/orders \ -H "Authorization: Bearer $RAVI" \ -H "Content-Type: application/json" \ -d '{"email":"amit@example.com", "items":[{"productId":1,"quantity":1}]}'HTTP/1.1 201 CreatedLocation: /api/orders/1{ "id": 1, "email": "ravi@example.com", "status": "Placed", "total": 2499.0, ... }74.6 Owner check
- Login is not enough: Ravi can guess the id of Amit's order.
- If the user is not admin and the email does not match, return NotFound so the order's existence does not leak.
- List and cancel use the same filter.
static async Task<Results<Ok<OrderDto>, NotFound>> GetById(int id, ClaimsPrincipal user, OrderService orders){ var order = await orders.FindAsync(id); if (order is null || (!user.IsAdmin() && order.Email != user.Email())) return TypedResults.NotFound(); return TypedResults.Ok(order.ToDto());}$ curl -i localhost:5074/api/orders/2 \ -H "Authorization: Bearer $RAVI"HTTP/1.1 404 Not FoundContent-Type: application/problem+json $ curl -i localhost:5074/api/orders/2 \ -H "Authorization: Bearer $AMIT"HTTP/1.1 200 OK{ "id": 2, "email": "amit@example.com", "status": "Placed", "total": 4998.0, ... }- Step 1
1.Login: token with sub + role
- Step 2
2.JwtBearer checks signature, issuer and expiry
- Step 3
3.Policy decides: 401 (no/invalid token) or 403 (wrong role)
- Step 4
4.Handler reads sub claim and does the owner check
- Step 5
5.Owner or admin -> 200, otherwise 404
Identity comes from the token, never from the body
74.7 Checkpoint: customer creates a product
- GET endpoints for products stay open; write endpoints sit in an admin group with RequireAuthorization("admin").
- Amit's customer token is valid but has no admin role -> 403 Forbidden; the admin token gets 201.
var g = app.MapGroup("/api/products") .WithTags("Products");g.MapGet("/", GetAll);g.MapGet("/{id:int}", GetById); var admin = g.MapGroup("") .RequireAuthorization("admin");admin.MapPost("/", Create);admin.MapPut("/{id:int}", Update);admin.MapDelete("/{id:int}", Delete);$ curl -i localhost:5074/api/products \ -H "Authorization: Bearer $AMIT" \ -H "Content-Type: application/json" \ -d '{"name":"Mixer Grinder","price":2499,"stock":5}'HTTP/1.1 403 Forbidden $ curl -i localhost:5074/api/products \ -H "Authorization: Bearer $ADMIN" \ -H "Content-Type: application/json" \ -d '{"name":"Mixer Grinder","price":2499,"stock":5}'HTTP/1.1 201 CreatedLocation: /api/products/174.8 Unit test: real OrderService
- Runs the real OrderService with a SQLite in-memory database and a FakeTimeProvider (fixed time).
- Checks the total comes from the server price (4998), CreatedAt equals the fake clock, and stock went 5 -> 3.
[Fact]public async Task Place_UsesServerPrice(){ var sut = new OrderService(db, clock); var result = await sut.PlaceAsync( "amit@example.com", new([new(1, 2)])); result.Order!.Total.ShouldBe(4998m); result.Order.CreatedAt .ShouldBe(clock.GetUtcNow()); db.Products.AsNoTracking().Single() .Stock.ShouldBe(3);}74.9 Integration test: WebApplicationFactory
- WebApplicationFactory runs the whole app in memory.
- ClientFor gives an HttpClient with a real JWT from the app's own TokenService.
- Amit places an order, Ravi GETs its Location: expects 404. Removing the owner check fails this test at once.
[Fact]public async Task OtherCustomersOrder_Returns404(){ var amit = app.ClientFor("amit@example.com"); var ravi = app.ClientFor("ravi@example.com"); var res = await amit .PostAsJsonAsync("/api/orders", Body); var peek = await ravi .GetAsync(res.Headers.Location); peek.StatusCode.ShouldBe(HttpStatusCode.NotFound);}$ dotnet test --logger "console;verbosity=normal" Passed OrderServiceTests.Place_UsesServerPrice Passed OrderServiceTests.Place_MoreThanStock_Fails Passed OrderServiceTests.Cancel_OtherCustomer_IsNull Passed OrdersApiTests.CreateProduct_AsCustomer_Returns403 Passed OrdersApiTests.OtherCustomersOrder_Returns404 Passed OrdersApiTests.Place_TakesEmailFromToken Passed OrdersApiTests.Place_WithoutToken_Returns401Test Run Successful.Total tests: 7 Passed: 7| Test type | What runs | Good for |
|---|---|---|
| Unit | OrderService + SQLite in-memory + FakeTimeProvider | Business rules: price, stock, cancel |
| Integration | Whole app via WebApplicationFactory + real token | Auth: 401, 403, owner check, email from token |
74.10 Docker: multi-stage image
- Build stage: copy csproj + tool manifest first and restore (layer caching), then publish.
- dotnet ef migrations bundle creates efbundle, which applies migrations without the SDK.
- Runtime stage: aspnet image only, /data owned by the app user, non-root USER $APP_UID.
- Connection string points to /data/orders.db (a volume); the JWT key is not in the image.
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS buildWORKDIR /srcCOPY dotnet-tools.json .COPY src/OrderApi/OrderApi.csproj src/OrderApi/RUN dotnet tool restore \ && dotnet restore src/OrderApiCOPY src/OrderApi/ src/OrderApi/RUN dotnet publish src/OrderApi -c Release \ --no-restore -o /appRUN dotnet ef migrations bundle \ --project src/OrderApi -o /app/efbundle$ docker build -t order-api-c74 .#16 [build 8/8] RUN dotnet ef migrations bundle ...#16 13.21 Building bundle...#16 39.65 Done. Migrations Bundle: /app/efbundleFROM mcr.microsoft.com/dotnet/aspnet:10.0WORKDIR /appRUN mkdir /data && chown $APP_UID /dataCOPY --from=build /app .USER $APP_UIDENV ConnectionStrings__Orders=\"Data Source=/data/orders.db"EXPOSE 8080ENTRYPOINT ["dotnet", "OrderApi.dll"]$ docker images order-api-c74IMAGE DISK USAGE CONTENT SIZEorder-api-c74:latest 451MB 130MB74.11 Running: migrations first, then the app
- A one-off container runs ./efbundle on the volume, applies migrations and exits.
- The app container uses the same volume and gets Jwt__Key from an environment variable.
- Without the key the app fails fast with a clear error.
docker volume create orders-c74 # 1. migrations: once, before the appdocker run --rm -v orders-c74:/data \ --entrypoint ./efbundle order-api-c74 # 2. app: secret key from an env vardocker run -d -p 5074:8080 \ -v orders-c74:/data \ -e Jwt__Key=$JWT_KEY \ --name order-api-c74 order-api-c74$ docker run --rm -v orders-c74:/data \ --entrypoint ./efbundle order-api-c74Applying migration '20261106223940_InitialCreate'.Done. $ docker logs order-api-c74 Now listening on: http://[::]:8080 Hosting environment: Production$ curl -i localhost:5074/api/ordersHTTP/1.1 401 UnauthorizedWWW-Authenticate: Bearer $ docker run -v orders-c74:/data order-api-c74Unhandled exception.System.InvalidOperationException: Jwt:Key is missing.- Step 1
1.git push -> GitHub Actions
- Step 2
2.dotnet test -c Release (7 tests)
- Step 3
3.docker build (catches a broken Dockerfile)
- Step 4
4.Run efbundle once on the volume
- Step 5
5.Start the app container with Jwt__Key from env
Migrations are a separate step, secrets come from the environment
74.12 Common mistake: Migrate() at app startup
// Wrong: DDL on every start, app needs schema rightsvar app = builder.Build(); // WRONG: schema change on every app startusing (var scope = app.Services.CreateScope()) scope.ServiceProvider .GetRequiredService<AppDbContext>() .Database.Migrate();// Right: Separate deploy step, once before the app# 1. migrations: once, before the appdocker run --rm -v orders-c74:/data \ --entrypoint ./efbundle order-api-c74 # 2. app: secret key from an env vardocker run -d -p 5074:8080 \ ...- Database.Migrate() on startup: every instance tries to change the schema, and the app user needs DDL rights.
- Run the bundle as a separate deploy step, once, before the app starts.
74.13 CI with GitHub Actions
- Runs on every push and pull request.
- dotnet test runs the 7 tests; docker build makes sure the Dockerfile still works.
- Pushing the image needs a registry login (skipped here); actionlint reports 0 errors.
name: order-api-cion: [push, pull_request]jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - uses: actions/setup-dotnet@v6 with: dotnet-version: 10.0.x - run: dotnet test -c Release - run: docker build -t order-api .# CI step, real run in mcr.microsoft.com/dotnet/sdk:10.0$ dotnet test -c ReleasePassed! - Failed: 0, Passed: 7, Skipped: 0, Total: 7 $ docker run --rm -v ./.github/workflows:/w \ rhysd/actionlint:1.7.12 -verbose /w/ci.ymlverbose: Found 0 parse errors in 0 ms for w/ci.ymlverbose: Found total 0 errors in 18 ms for w/ci.yml74.14 Common mistakes
- Thinking RequireAuthorization makes data safe: it only checks login, not ownership. Missing owner check = IDOR bug.
- Taking identity (email, user id) from the request body.
- Baking secrets like the JWT key into the image or appsettings.
- Running migrations from app startup.
74.15 Interview tips
- Say: JWT bearer auth; the email comes from the sub claim; every order has an owner check; admin work has a policy.
- Explain 401 vs 403, and why you return 404 for someone else's order (IDOR).
- Tests: unit with SQLite in-memory + fake clock, integration with WebApplicationFactory and a real token.
- Deploy: multi-stage Docker image, separate migrations bundle step, secrets from env, GitHub Actions on every push.