Recipe 13.5 · Python
Authentication Headers and Tokens
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
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.
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.
Requirements: Python 3.12+. Install: pip install httpx
"""New token per call, written onto a shared client's default headers
Source: ImproveCode, Chapter 13, Recipe 13.5 "Authentication Headers and Tokens"
Section: The way it's often written
Book page: 293 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
DefaultRequestHeaders.Authorization -> mutating httpx.AsyncClient.headers, which every
concurrent request on the shared client sees (the same race as in C#).
"""
from __future__ import annotations
import httpx
class InvoiceService:
def __init__(self, shared_client: httpx.AsyncClient) -> None:
self._shared_client = shared_client
# Not to copy: a token per call, and a header race on a shared client
async def get_invoices(self) -> str:
token = await self.get_new_token()
self._shared_client.headers["Authorization"] = f"Bearer {token}"
response = await self._shared_client.get("invoices")
response.raise_for_status()
return response.text
async def get_new_token(self) -> str:
# Calls the token endpoint every time (not shown in the book).
raise NotImplementedError
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.
Wiring it to a typed client in Program.cs:
Requirements: Python 3.12+. Install: pip install pydantic
"""Client-credentials options, token provider contract and token response
Source: ImproveCode, Chapter 13, Recipe 13.5 "Authentication Headers and Tokens"
Section: The improved recipe
Book page: 293-294 -- original C# listing
Converted from C# to Python.
DataAnnotations options -> pydantic model ([Required] string -> min_length=1);
interface -> typing.Protocol; JsonPropertyName record -> pydantic model whose field
names already match the snake_case JSON keys.
"""
from __future__ import annotations
from typing import Protocol
from pydantic import AnyHttpUrl, BaseModel, ConfigDict, Field
class ClientCredentialsOptions(BaseModel):
model_config = ConfigDict(frozen=True)
token_endpoint: AnyHttpUrl
client_id: str = Field(min_length=1)
client_secret: str = Field(min_length=1)
scope: str | None = None
class IAccessTokenProvider(Protocol):
async def get_token(self) -> str: ...
def invalidate(self) -> None: ...
class TokenResponse(BaseModel):
model_config = ConfigDict(frozen=True)
access_token: str
expires_in: int
Requirements: Python 3.12+. Install: pip install httpx
"""Cached client-credentials token provider with single-flight refresh
Source: ImproveCode, Chapter 13, Recipe 13.5 "Authentication Headers and Tokens"
Section: The improved recipe
Book page: 294-295 -- original C# listing
Converted from C# to Python.
SemaphoreSlim(1,1) -> asyncio.Lock (double-checked); TimeProvider -> an injectable
clock callable; IHttpClientFactory.CreateClient(name) -> an injected httpx.AsyncClient.
asyncio.Lock holds no OS resources, so the IDisposable part has no counterpart.
"""
from __future__ import annotations
import asyncio
from collections.abc import Callable
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
import httpx
from p293_r13_5_client_credentials_options_contracts import (
ClientCredentialsOptions,
TokenResponse,
)
@dataclass(frozen=True)
class _CachedToken:
value: str
expires_at: datetime
def system_clock() -> datetime:
return datetime.now(UTC)
class ClientCredentialsTokenProvider:
"""Implements IAccessTokenProvider."""
HTTP_CLIENT_NAME = "token-endpoint"
_REFRESH_MARGIN = timedelta(minutes=1)
def __init__(
self,
http: httpx.AsyncClient,
options: ClientCredentialsOptions,
time: Callable[[], datetime] = system_clock) -> None:
self._http = http
self._options = options
self._time = time
self._refresh_lock = asyncio.Lock()
self._cached: _CachedToken | None = None
async def get_token(self) -> str:
current = self._cached
if current is not None and not self._is_expiring(current):
return current.value
async with self._refresh_lock:
current = self._cached
if current is None or self._is_expiring(current):
current = await self._request_token()
self._cached = current
return current.value
def invalidate(self) -> None:
self._cached = None
def _is_expiring(self, token: _CachedToken) -> bool:
return self._time() >= token.expires_at - self._REFRESH_MARGIN
async def _request_token(self) -> _CachedToken:
o = self._options
form = {
"grant_type": "client_credentials",
"client_id": o.client_id,
"client_secret": o.client_secret,
}
if o.scope and o.scope.strip():
form["scope"] = o.scope
response = await self._http.post(str(o.token_endpoint), data=form)
response.raise_for_status()
body = response.content.strip()
if not body or body == b"null":
raise RuntimeError("Token endpoint returned an empty body.")
token = TokenResponse.model_validate_json(body)
return _CachedToken(
token.access_token,
self._time() + timedelta(seconds=token.expires_in))
Requirements: Python 3.12+. Install: pip install httpx
"""Bearer-token request handler that invalidates the token on 401
Source: ImproveCode, Chapter 13, Recipe 13.5 "Authentication Headers and Tokens"
Section: The improved recipe
Book page: 295-296 -- original C# listing
Converted from C# to Python.
DelegatingHandler -> httpx.Auth with an async auth flow: the token is set on each
request (never on the shared client's default headers) and a 401 invalidates it.
"""
from __future__ import annotations
from collections.abc import AsyncGenerator
import httpx
from p293_r13_5_client_credentials_options_contracts import IAccessTokenProvider
class BearerTokenAuth(httpx.Auth):
def __init__(self, tokens: IAccessTokenProvider) -> None:
self._tokens = tokens
async def async_auth_flow(
self, request: httpx.Request) -> AsyncGenerator[httpx.Request, httpx.Response]:
token = await self._tokens.get_token()
request.headers["Authorization"] = f"Bearer {token}"
response = yield request
if response.status_code == httpx.codes.UNAUTHORIZED:
# Revoked or rotated early: fetch a new one next time.
self._tokens.invalidate()
Requirements: Python 3.12+. Install: pip install httpx
"""Register client-credentials token services
Source: ImproveCode, Chapter 13, Recipe 13.5 "Authentication Headers and Tokens"
Section: The improved recipe
Book page: 296 -- original C# listing
Converted from C# to Python.
DI registrations -> a function that validates the options at startup (pydantic) and
wires one named httpx.AsyncClient, one singleton token provider and a factory for the
(transient) BearerTokenAuth; TimeProvider.System -> a UTC clock function.
"""
from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any
import httpx
from p293_r13_5_client_credentials_options_contracts import (
ClientCredentialsOptions,
IAccessTokenProvider,
)
from p294_r13_5_cached_client_credentials_token_provider import (
ClientCredentialsTokenProvider,
system_clock,
)
from p295_r13_5_bearer_token_auth_handler import BearerTokenAuth
@dataclass(frozen=True)
class ClientCredentialsTokens:
token_http: httpx.AsyncClient # the "token-endpoint" named client
provider: IAccessTokenProvider # singleton
def bearer_token_handler(self) -> BearerTokenAuth: # transient
return BearerTokenAuth(self.provider)
def add_client_credentials_tokens(section: Mapping[str, Any]) -> ClientCredentialsTokens:
options = ClientCredentialsOptions.model_validate(dict(section)) # ValidateOnStart
token_http = httpx.AsyncClient()
provider = ClientCredentialsTokenProvider(token_http, options, system_clock)
return ClientCredentialsTokens(token_http, provider)
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Wire bearer tokens and resilience into the customer API client
Source: ImproveCode, Chapter 13, Recipe 13.5 "Authentication Headers and Tokens"
Section: The improved recipe
Book page: 296 -- original C# listing
Converted from C# to Python.
Startup fragment wrapped in a function. AddStandardResilienceHandler -> ResilientTransport
with default options; AddHttpMessageHandler<BearerTokenHandler> -> httpx auth. Note that
httpx runs auth outside the transport, so the token is fetched once per logical request
rather than once per retry attempt as in the .NET handler order.
"""
from __future__ import annotations
from collections.abc import Mapping
from typing import Any
from p278_r13_1_typed_customer_api_client import CustomerApiClient
from p279_r13_1_register_customer_api_client import add_customer_api
from p282_r13_2_standard_resilience_handler import (
ResilientTransport,
StandardResilienceOptions,
)
from p296_r13_5_register_client_credentials_tokens import add_client_credentials_tokens
def configure_customer_api(configuration: Mapping[str, Any]) -> CustomerApiClient:
tokens = add_client_credentials_tokens(configuration["PartnerAuth"])
customer_api = add_customer_api(configuration)
customer_api.transport = ResilientTransport(StandardResilienceOptions())
customer_api.auth = tokens.bearer_token_handler()
return customer_api.build()
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
AddHttpClientconfigure 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
Authorizationheader. - 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 throughHttpRequestMessage.Options. - Use a library for user tokens. For tokens on behalf of a signed-in user, or for Microsoft
Entra ID, use
Microsoft.Identity.Webor MSAL. They handle caching, refresh and certificates. The provider here is for the common machine-to-machine case.