LESSON 14 OF 18

Authentication and Authorization Integration Tests

Use WebApplicationFactory to test identity, claims, roles, policies, and 401/403 behavior for protected order endpoints.

55 dk 65

Introduction

In the previous lesson, we tested API validation, error handling, and ProblemDetails responses. We will now verify the security boundaries of the order API. A protected endpoint must not only return a successful HTTP response; it must also prove that the correct user can access the correct resource.

This lesson uses WebApplicationFactory to create authentication and authorization scenarios in integration tests. We will build test users with names, user identifiers, roles, and permission claims. Then we will compare anonymous users, authenticated users without sufficient permissions, and fully authorized users.

Assume that the order API contains these endpoints:

  • GET /api/orders/{id}: available to authenticated users.
  • POST /api/orders: requires the Orders.Write policy.
  • DELETE /api/orders/{id}: requires the Admin role.

This technique lets us test the application’s authentication and authorization pipeline without starting a real identity provider for every test. We are not testing the JWT provider’s signing algorithm here. We are testing how our application behaves when a valid user identity is available.

Authentication versus authorization

Authentication determines who is making a request. ASP.NET Core represents that identity with a ClaimsPrincipal containing a ClaimsIdentity. When authentication succeeds, the framework populates HttpContext.User.

Authorization determines whether that identity can access a resource. [Authorize] requires an authenticated user. [Authorize(Roles = "Admin")] checks a role. A policy can evaluate one or more claims and can express more precise application rules.

The distinction should also appear in test names. UnauthenticatedUser_Returns401 describes an authentication scenario. AuthenticatedUserWithoutWritePermission_Returns403 describes an authorization scenario. Combining both into one test can hide which security layer is failing.

Application security configuration

First, define the security rules used by the sample endpoints:

builder.Services.AddAuthorization(options => {    options.AddPolicy("Orders.Write", policy =>        policy.RequireClaim("permission", "Orders.Write")); }); app.MapGet("/api/orders/{id:int}", GetOrder)   .RequireAuthorization(); app.MapPost("/api/orders", CreateOrder)   .RequireAuthorization("Orders.Write"); app.MapDelete("/api/orders/{id:int}", DeleteOrder)   .RequireAuthorization(policy => policy.RequireRole("Admin"));

With controllers, the same rules can be expressed with attributes:

[ApiController] [Route("api/orders")] public sealed class OrdersController : ControllerBase {    [HttpGet("{id:int}")]    [Authorize]    public IActionResult Get(int id) => Ok();    [HttpPost]    [Authorize(Policy = "Orders.Write")]    public IActionResult Post(CreateOrderRequest request) => Ok();    [HttpDelete("{id:int}")]    [Authorize(Roles = "Admin")]    public IActionResult Delete(int id) => NoContent(); }

Authentication middleware must run before authorization middleware:

app.UseAuthentication(); app.UseAuthorization();

For API endpoints, an unauthenticated request normally produces 401 Unauthorized, while an authenticated user who does not satisfy the authorization rule receives 403 Forbidden. Preserving this distinction is one of the main goals of the tests.

Creating a test authentication handler

It is possible to create a real JWT for every test, but that often introduces unnecessary setup. Instead, register a custom authentication scheme in the test host. The handler reads test-user information from request headers and creates an AuthenticationTicket.

The following handler uses X-Test-User, X-Test-Roles, and X-Test-Permissions. These headers are for tests only and must never be accepted by the production authentication pipeline.

public sealed class TestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions> {    public const string Scheme = "TestScheme";    public TestAuthHandler(        IOptionsMonitor<AuthenticationSchemeOptions> options,        ILoggerFactory logger,        UrlEncoder encoder)        : base(options, logger, encoder)    {    }    protected override Task<AuthenticateResult> HandleAuthenticateAsync()    {        if (!Request.Headers.TryGetValue("X-Test-User", out var userId) ||            StringValues.IsNullOrEmpty(userId))        {            return Task.FromResult(AuthenticateResult.NoResult());        }        var claims = new List<Claim>        {            new(ClaimTypes.NameIdentifier, userId.ToString()),            new(ClaimTypes.Name, $"user-{userId}")        };        AddClaims("X-Test-Roles", ClaimTypes.Role, claims);        AddClaims("X-Test-Permissions", "permission", claims);        var identity = new ClaimsIdentity(claims, Scheme);        var principal = new ClaimsPrincipal(identity);        var ticket = new AuthenticationTicket(principal, Scheme);        return Task.FromResult(AuthenticateResult.Success(ticket));    }    private void AddClaims(string headerName, string claimType, List<Claim> claims)    {        if (!Request.Headers.TryGetValue(headerName, out var values))            return;        foreach (var value in values.ToString()                     .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))        {            claims.Add(new Claim(claimType, value));        }    } }

The scheme name must be registered as the default authentication scheme in the test host. If the names do not match, the handler may never run and the request can unexpectedly return 401.

Replacing the scheme in WebApplicationFactory

Use ConfigureTestServices to replace the application’s real authentication registration with the test scheme:

private HttpClient CreateClientForUser(    string? userId = null,    string[]? roles = null,    string[]? permissions = null) {    var client = _factory.WithWebHostBuilder(builder =>    {        builder.ConfigureTestServices(services =>        {            services.AddAuthentication(options =>            {                options.DefaultAuthenticateScheme = TestAuthHandler.Scheme;                options.DefaultChallengeScheme = TestAuthHandler.Scheme;            })            .AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(                TestAuthHandler.Scheme, _ => { });        });    }).CreateClient();    if (userId is not null)    {        client.DefaultRequestHeaders.Add("X-Test-User", userId);    }    if (roles is not null)    {        client.DefaultRequestHeaders.Add("X-Test-Roles", string.Join(',', roles));    }    if (permissions is not null)    {        client.DefaultRequestHeaders.Add(            "X-Test-Permissions", string.Join(',', permissions));    }    return client; }

Creating a separate HttpClient for each scenario prevents user headers from leaking between tests. If you share a client, clear all identity headers before the next request. Shared mutable client state can also create race conditions when tests run in parallel.

Authentication scenarios

1. Anonymous user

[Fact] public async Task GetOrder_WithoutIdentity_Returns401() {    var client = CreateClientForUser();    var response = await client.GetAsync("/api/orders/42");    response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); }

Because the handler returns NoResult, the request is not authenticated. The endpoint’s [Authorize] or RequireAuthorization rule rejects it.

2. Authenticated user

[Fact] public async Task GetOrder_WithAuthenticatedUser_Returns200() {    var client = CreateClientForUser(userId: "customer-17");    var response = await client.GetAsync("/api/orders/42");    response.StatusCode.Should().Be(HttpStatusCode.OK); }

This test validates the authentication chain and the endpoint’s integration with the existing order data setup. The database fixture should prepare order 42 using the integration-test infrastructure from the previous lessons.

Testing roles and policies

Insufficient role

[Fact] public async Task DeleteOrder_NonAdminUser_Returns403() {    var client = CreateClientForUser(        userId: "customer-17",        roles: ["Customer"]);    var response = await client.DeleteAsync("/api/orders/42");    response.StatusCode.Should().Be(HttpStatusCode.Forbidden); }

The user is authenticated, so the result must be 403, not 401. Having a different role does not satisfy the Admin requirement.

User with the required role

[Fact] public async Task DeleteOrder_AdminUser_Returns204() {    var client = CreateClientForUser(        userId: "admin-1",        roles: ["Admin"]);    var response = await client.DeleteAsync("/api/orders/42");    response.StatusCode.Should().Be(HttpStatusCode.NoContent); }

Missing policy claim

[Fact] public async Task CreateOrder_WithoutWritePermission_Returns403() {    var client = CreateClientForUser(        userId: "customer-17",        permissions: ["Orders.Read"]);    using var content = JsonContent.Create(new    {        productId = 5,        quantity = 2    });    var response = await client.PostAsync("/api/orders", content);    response.StatusCode.Should().Be(HttpStatusCode.Forbidden); }

User with the policy claim

[Fact] public async Task CreateOrder_WithWritePermission_Returns201() {    var client = CreateClientForUser(        userId: "customer-17",        permissions: ["Orders.Write"]);    using var content = JsonContent.Create(new    {        productId = 5,        quantity = 2    });    var response = await client.PostAsync("/api/orders", content);    response.StatusCode.Should().Be(HttpStatusCode.Created); }

Make sure the claim type is exactly the one used by the policy. If the policy searches for a permission claim while the handler creates a different claim type, the request will correctly fail authorization.

When should you use JWT-based tests?

A custom handler is fast and deterministic. It is usually sufficient for testing application authorization rules. Add real or realistic JWT tests when you also need to verify:

  • issuer and audience validation;
  • signature key and algorithm validation;
  • expiration, clock skew, and expired-token behavior;
  • mapping from JWT claims to the claims used by the application.

These tests require more configuration and are usually slower. A balanced suite can use a test handler for most protected endpoint tests and a smaller set of JWT-focused tests for the authentication provider contract.

Common mistakes

  • Confusing 401 and 403: 401 means that authentication is missing or unsuccessful; 403 means that the known user is not allowed to perform the operation.
  • Using the wrong scheme name: The test registration must configure the same scheme as the default authenticate and challenge scheme expected by the test host.
  • Using the wrong role claim type: RequireRole evaluates role claims. The claim type must match the framework and application configuration.
  • Leaving the real authentication handler active: If the JWT or cookie handler remains active, the test might execute real validation instead of the intended test handler.
  • Allowing test headers in production: The test handler and its headers should exist only in test code or a strictly isolated test environment.
  • Following redirects automatically: For cookie authentication, set AllowAutoRedirect = false when you need to inspect the original response. API tests generally expect 401 or 403.
  • Testing only success: For each protected endpoint, consider anonymous, authenticated-but-forbidden, and authorized scenarios.

Practice exercise

Complete the following exercise:

  1. Verify that an anonymous request to GET /api/orders/{id} returns 401.
  2. Verify that a user with the Customer role can access the same endpoint and receives 200.
  3. Verify that a user without the Admin role receives 403 from DELETE /api/orders/{id}.
  4. Test the POST policy with Orders.Read and Orders.Write separately.
  5. Use descriptive test names and verify the database change in addition to the response status code.

Conclusion

In this lesson, we built authentication and authorization integration tests using real HTTP requests. We customized the WebApplicationFactory test host, created controlled users with a custom AuthenticationHandler, and verified how claims, roles, and policies affect endpoint behavior.

The central distinction is simple: authentication identifies the user, while authorization decides what that user can do. Your test suite should therefore contain deliberate 401, 403, and successful-response scenarios. In the next stage, these security tests can be combined with database lifecycle management, reusable fixtures, and a larger test-suite organization strategy.

Sources