IC Improve Code Recipes

Recipe 13.5 · C#

Authentication Headers and Tokens

Problem

The partner API wants an OAuth 2.0 bearer token from a client-credentials flow. Tokens last an hour. You need to attach a valid token to every request, refresh it before it expires, and not call the token endpoint on every request.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not to copy: a token per call, and a header race on a shared client
public async Task<string> GetInvoicesAsync()
{
    string token = await GetNewTokenAsync();
    _sharedClient.DefaultRequestHeaders.Authorization =
        new AuthenticationHeaderValue("Bearer", token);
    return await _sharedClient.GetStringAsync("invoices");
}

This calls the token endpoint for every request, which doubles your traffic and can trip the identity provider's rate limit. Worse, DefaultRequestHeaders belongs to the shared client, and it is not thread-safe to change while requests are in flight. Two concurrent requests for different tenants can go out with each other's tokens.

The improved recipe

Put the token logic in a singleton that caches the token and refreshes it a minute before expiry, and attach it per request in a DelegatingHandler.

C#
using System;
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;

namespace ImproveCode.Http;

public sealed class ClientCredentialsOptions
{
    [Required]
    public Uri? TokenEndpoint { get; set; }

    [Required]
    public string ClientId { get; set; } = "";

    [Required]
    public string ClientSecret { get; set; } = "";

    public string? Scope { get; set; }
}

public interface IAccessTokenProvider
{
    ValueTask<string> GetTokenAsync(CancellationToken ct);
    void Invalidate();
}

internal sealed record TokenResponse(
    [property: JsonPropertyName("access_token")] string AccessToken,
    [property: JsonPropertyName("expires_in")] int ExpiresIn);
C#
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;

namespace ImproveCode.Http;

public sealed class ClientCredentialsTokenProvider(
    IHttpClientFactory httpFactory,
    IOptions<ClientCredentialsOptions> options,
    TimeProvider time) : IAccessTokenProvider, IDisposable
{
    public const string HttpClientName = "token-endpoint";
    private static readonly TimeSpan RefreshMargin =
        TimeSpan.FromMinutes(1);

    private readonly SemaphoreSlim _refreshLock = new(1, 1);
    private volatile CachedToken? _cached;

    public async ValueTask<string> GetTokenAsync(CancellationToken ct)
    {
        CachedToken? current = _cached;
        if (current is not null && !IsExpiring(current))
        {
            return current.Value;
        }

        await _refreshLock.WaitAsync(ct);
        try
        {
            current = _cached;
            if (current is null || IsExpiring(current))
            {
                current = await RequestTokenAsync(ct);
                _cached = current;
            }

            return current.Value;
        }
        finally
        {
            _refreshLock.Release();
        }
    }

    public void Invalidate() => _cached = null;

    public void Dispose() => _refreshLock.Dispose();

    private bool IsExpiring(CachedToken token) =>
        time.GetUtcNow() >= token.ExpiresAt - RefreshMargin;

    private async Task<CachedToken> RequestTokenAsync(
        CancellationToken ct)
    {
        ClientCredentialsOptions o = options.Value;
        var form = new Dictionary<string, string>
        {
            ["grant_type"] = "client_credentials",
            ["client_id"] = o.ClientId,
            ["client_secret"] = o.ClientSecret,
        };
        if (!string.IsNullOrWhiteSpace(o.Scope))
        {
            form["scope"] = o.Scope;
        }

        HttpClient http = httpFactory.CreateClient(HttpClientName);
        using var content = new FormUrlEncodedContent(form);
        using HttpResponseMessage response =
            await http.PostAsync(o.TokenEndpoint, content, ct);
        response.EnsureSuccessStatusCode();

        TokenResponse token = await response.Content
                .ReadFromJsonAsync<TokenResponse>(ct)
            ?? throw new InvalidOperationException(
                "Token endpoint returned an empty body.");

        return new CachedToken(
            token.AccessToken,
            time.GetUtcNow().AddSeconds(token.ExpiresIn));
    }

    private sealed record CachedToken(
        string Value, DateTimeOffset ExpiresAt);
}
C#
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;

namespace ImproveCode.Http;

public sealed class BearerTokenHandler(IAccessTokenProvider tokens)
    : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken ct)
    {
        string token = await tokens.GetTokenAsync(ct);
        request.Headers.Authorization =
            new AuthenticationHeaderValue("Bearer", token);

        HttpResponseMessage response = await base.SendAsync(request, ct);
        if (response.StatusCode == HttpStatusCode.Unauthorized)
        {
            // Revoked or rotated early: fetch a new one next time.
            tokens.Invalidate();
        }

        return response;
    }
}
C#
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace ImproveCode.Http;

public static class TokenServiceCollectionExtensions
{
    public static IServiceCollection AddClientCredentialsTokens(
        this IServiceCollection services, IConfiguration section)
    {
        services.AddOptions<ClientCredentialsOptions>()
            .Bind(section)
            .ValidateDataAnnotations()
            .ValidateOnStart();

        services.TryAddSingleton(TimeProvider.System);
        services.AddHttpClient(
            ClientCredentialsTokenProvider.HttpClientName);
        services.AddSingleton<IAccessTokenProvider,
            ClientCredentialsTokenProvider>();
        services.AddTransient<BearerTokenHandler>();
        return services;
    }
}

Wiring it to a typed client in Program.cs:

C#
builder.Services.AddClientCredentialsTokens(
    builder.Configuration.GetSection("PartnerAuth"));

IHttpClientBuilder customerApi =
    builder.Services.AddCustomerApi(builder.Configuration);
customerApi.AddStandardResilienceHandler();
customerApi.AddHttpMessageHandler<BearerTokenHandler>();

How it works

The token provider is a singleton, so there is one cache for the whole process. The fast path reads a single volatile reference to an immutable CachedToken record. No lock is taken while the token is fresh, which is almost every call. When the token is missing or within a minute of expiry, callers queue on a SemaphoreSlim, and the first one through fetches a new token. The others find the fresh token on their second check and return without a network call. Refreshing a minute early avoids sending a token that expires in flight.

The provider uses IHttpClientFactory with a named client rather than a typed client. A typed client is transient, and a singleton that held one would keep its handler forever, which is the pitfall from Recipe 13.1. TimeProvider makes expiry testable: in a unit test, pass a FakeTimeProvider from the Microsoft.Extensions.TimeProvider.Testing package and advance the clock.

BearerTokenHandler sets the header on the HttpRequestMessage, which belongs to one request, so there is no race. On a 401 it drops the cached token, so the next request fetches a new one. The handler is registered as transient, as the factory requires for message handlers.

Handlers run in the order they are added. Adding the resilience handler first and the bearer handler second puts the token step inside the retry loop, so each attempt checks the token. If a token expires between a first attempt and its retry, the retry gets a fresh one.

Variations and pitfalls

  • API keys and basic authentication. A fixed header that never changes can be set once in the AddHttpClient configure delegate: http.DefaultRequestHeaders.Add("X-Api-Key", key). That is safe because it happens when the client is created, before any request.
  • Never log the token or the secret. Both are credentials. If you log outgoing requests, redact the Authorization header.
  • Per-tenant tokens. If each tenant has its own credentials, key the cache by tenant ID with a ConcurrentDictionary<string, CachedToken>, and pass the tenant through HttpRequestMessage.Options.
  • Use a library for user tokens. For tokens on behalf of a signed-in user, or for Microsoft Entra ID, use Microsoft.Identity.Web or MSAL. They handle caching, refresh and certificates. The provider here is for the common machine-to-machine case.