LESSON 19 OF 20

19. Security, API Protection, and Service-to-Service Trust

Apply JWT authentication, policy-based authorization, public and internal endpoint boundaries, service-to-service tokens, and secure secret management in ASP.NET Core microservices.

50 dk 30

Introduction

The ability of services to communicate in a distributed system does not mean that every request should be trusted. An endpoint being discoverable through service discovery or visible in the Aspire Dashboard does not make it public. In this lesson, we will add a security layer to our Catalog, Order, and Inventory services.

Our goal is to answer four questions: Who is making the request? Has that identity been authenticated? Is the identity allowed to perform the requested operation? Are secrets and tokens managed safely while the request is processed?

In ASP.NET Core, authentication establishes identity, while authorization decides whether an authenticated identity may access a resource. For APIs, a common approach is to validate an OAuth 2.0 or OpenID Connect-compatible access token with the JWT Bearer handler. In production, use an established identity provider rather than generating arbitrary JWTs from a custom username-and-password endpoint.

1. Define public and internal endpoint boundaries

Start by classifying endpoints according to their intended callers:

Endpoint typeExampleProtection
PublicGET /catalog/productsAnonymous access or a low-privilege user token
AuthenticatedPOST /ordersValid access token
PrivilegedDELETE /catalog/products/{id}Admin role or an appropriate scope
InternalPOST /inventory/reservationsService identity and narrowly defined permission

Internal endpoints must not be protected only by hiding their URLs from the internet. Network restrictions are useful, but every service should still validate the incoming token, check the expected issuer and audience, and evaluate the required permissions.

2. Add JWT Bearer authentication to the Catalog API

Add the JWT Bearer package to the Catalog API project:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Configure authentication and authorization in Program.cs. The example assumes that tokens are issued by https://identity.example.local and that the Catalog API uses catalog-api as its audience.

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

var builder = WebApplication.CreateBuilder(args);

builder.AddServiceDefaults();

builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = builder.Configuration["Authentication:Authority"]!;
        options.Audience = builder.Configuration["Authentication:Audience"]!;
        options.RequireHttpsMetadata = !builder.Environment.IsDevelopment();
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true
        };
    });

builder.Services.AddAuthorizationBuilder()
    .SetFallbackPolicy(new Microsoft.AspNetCore.Authorization.AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build())
    .AddPolicy("catalog.read", policy =>
        policy.RequireClaim("scope", "catalog.read"))
    .AddPolicy("catalog.write", policy =>
        policy.RequireClaim("scope", "catalog.write"));

var app = builder.Build();

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

app.MapDefaultEndpoints();

app.MapGet("/catalog/products", () =>
    Results.Ok(new[] { "keyboard", "monitor" }))
    .RequireAuthorization("catalog.read");

app.MapPost("/catalog/products", () =>
    Results.Created("/catalog/products/42", new { Id = 42 }))
    .RequireAuthorization("catalog.write");

app.MapGet("/catalog/health-details", () =>
    Results.Ok(new { Status = "healthy" }))
    .RequireAuthorization();

app.Run();

With SetFallbackPolicy, endpoints require authentication unless they explicitly opt out. This is a safe default because a newly added endpoint cannot accidentally become anonymous simply because an authorization attribute was forgotten.

app.MapGet("/catalog/version", () => Results.Ok("1.0"))
   .AllowAnonymous();

3. Understand the difference between authentication and authorization

An API generally returns 401 Unauthorized when no valid token is available. It returns 403 Forbidden when the token is valid but does not contain the required scope or role. This distinction is important for troubleshooting clients, gateways, and observability data.

  • 401: The token is missing, expired, invalidly signed, or has an unexpected issuer or audience.
  • 403: The token is valid, but the caller lacks the permission required by the endpoint.
  • 200: Both identity and authorization checks succeeded.

Instead of assigning a broad admin role to every operation, define policies that match the service capability. For example, the Catalog service may only require the catalog.write scope to delete a product. Adding an administrator role to the token would create unnecessary privilege.

4. Separate user identity from service identity in the Order API

The Order API may create an order on behalf of a user and then ask the Inventory API to reserve stock. These are two different trust relationships:

  1. A request from the end user to the Order API can use a delegated user access token.
  2. A request from the Order API to the Inventory API can use an application access token obtained through the client credentials flow.

Blindly forwarding a user token to every downstream service can give that token more audiences or scopes than necessary. If the downstream business operation does not require the user’s identity, the Order API should call Inventory using its own narrowly scoped service identity.

Keep token acquisition outside endpoint code by using an abstraction and a DelegatingHandler:

public interface IServiceAccessTokenProvider
{
    Task<string> GetTokenAsync(string audience, CancellationToken cancellationToken);
}

public sealed class ServiceTokenHandler(
    IServiceAccessTokenProvider tokenProvider) : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        var token = await tokenProvider.GetTokenAsync(
            "inventory-api", cancellationToken);

        request.Headers.Authorization =
            new System.Net.Http.Headers.AuthenticationHeaderValue(
                "Bearer", token);

        return await base.SendAsync(request, cancellationToken);
    }
}

Register the client as follows:

builder.Services.AddTransient<ServiceTokenHandler>();

builder.Services.AddHttpClient<InventoryClient>(client =>
{
    client.BaseAddress = new Uri("http://inventory-api");
})
.AddHttpMessageHandler<ServiceTokenHandler>();

The InventoryClient uses the service-discovered inventory-api address. The concrete implementation of IServiceAccessTokenProvider depends on the chosen identity provider. In production, cache a token securely until it is close to expiration rather than requesting a new token for every HTTP call.

5. Add an internal service policy

The Inventory API should allow stock reservation only for the Order API. In addition to the audience, check a scope or client claim:

builder.Services.AddAuthorizationBuilder()
    .AddPolicy("inventory.reserve", policy =>
    {
        policy.RequireAuthenticatedUser();
        policy.RequireClaim("scope", "inventory.reserve");
        policy.RequireClaim("client_id", "order-service");
    });

app.MapPost("/inventory/reservations", ReserveInventory)
   .RequireAuthorization("inventory.reserve");

This prevents any application holding a valid token from reserving inventory. Claim names and formats depend on the identity provider, so do not assume that every provider uses exactly the same claims. Document the token contract, validate it with integration tests using representative tokens, and never log the token itself.

6. Manage secrets and configuration in Aspire environments

Values such as issuer URLs, audiences, and client secrets must not be committed to source control. During development, use .NET User Secrets. In deployed environments, use the secret store supplied by the hosting platform:

dotnet user-secrets init --project src/Order/Order.Api

dotnet user-secrets set "Authentication:Authority" "https://identity.example.local" \
  --project src/Order/Order.Api

dotnet user-secrets set "Authentication:ClientSecret" "development-only-value" \
  --project src/Order/Order.Api

When defining resources in the Aspire AppHost, do not place secret values directly in source code or pass them as plain-text environment values. Use AppHost parameters and the secret mechanism provided by the runtime or deployment platform. The AppHost composes services and dependencies; it does not automatically make an identity provider trusted. Each API must validate its own tokens.

Separate development and production settings. Disabling HTTPS metadata checks may be acceptable temporarily for local development, but production token metadata and signing-key validation should use HTTPS. The Dashboard, health endpoints, and OpenAPI interfaces should also follow the security model of the environment in which they run.

7. Common mistakes

  • Using an ID token as an API access token: An ID token communicates identity to the client. API calls should use an access token issued for the API audience.
  • Trusting only the gateway: If a request can reach a service directly, that service must still perform authentication and authorization.
  • Disabling audience validation: A valid token issued for another API is not automatically valid for this API.
  • Committing secrets to Git: A deleted secret may remain in repository history. Use rotation and repository scanning.
  • Forwarding the user token to every internal service: Decide explicitly between delegated access and application access.
  • Making health and metrics endpoints public unintentionally: Expose only the minimal information required for liveness and protect detailed diagnostics.
  • Logging tokens: Never write Authorization headers, refresh tokens, or client secrets to logs.

8. Practice exercise

Complete the following exercise:

  1. Enable a fallback authorization policy in the Catalog API.
  2. Require catalog.read for GET /catalog/products and catalog.write for the product creation endpoint.
  3. Explicitly mark GET /catalog/version as anonymous.
  4. Add an Inventory policy that accepts only the order-service client with the inventory.reserve scope.
  5. Test the expected 401 and 403 responses for an invalid issuer, an incorrect audience, a missing scope, and an expired token.
  6. Log the request path, status code, and correlation information during testing, but never log token values.

Conclusion

In this lesson, we defined security boundaries for the microservices system, added JWT Bearer authentication, applied policy-based authorization, and separated public endpoints from internal endpoints. We also compared delegated user identity with application identity for the Order-to-Inventory call.

A secure Aspire application is not created merely because the AppHost starts all resources. Each service must validate tokens independently, accept only the scopes it needs, retrieve secrets through a secure channel, and document its trust relationships. In the final lesson, we will combine these practices with production readiness, deployment strategy, and an operational checklist.

Sources