OIDC Client Library
Introduction
The ProAuth OIDC Client library (ProAuth.Oidc.Client) provides a comprehensive set of tools for integrating .NET applications with ProAuth as an OpenID Connect identity provider. It handles OAuth 2.0 / OIDC protocol operations, token management, and secure API communication.
While the BFF package uses this library internally for browser-based applications, you can also use the OIDC Client directly for:
- Backend services requiring service-to-service authentication
- API gateways that need to manage tokens
- Custom authentication flows
- Token exchange scenarios
- Applications requiring direct OIDC protocol access
The .NET client and native client use dedicated routing parameters by default, including proauth_tenant on token requests. Use dedicated tenant/IdP settings and standard ui_locales; reserve acr_values for assurance. See authorization parameters and legacy routing.
Features
| Feature | Description |
|---|---|
| Token Management | Automatic token acquisition, caching, and refresh |
| Client Credentials | Service-to-service authentication |
| Token Exchange | RFC 8693 token exchange support |
| Token Introspection | Validate tokens via introspection endpoint |
| Token Revocation | Revoke access and refresh tokens |
| DPoP | Create RFC 9449 proofs for sender-constrained tokens |
| JWT-Secured Authorization Requests | Build signed request objects for authorization redirects and PAR |
| JWT Introspection Responses | Validate signed or encrypted JWT introspection responses |
| Discovery | Automatic OIDC discovery document handling |
| Distributed Storage | Pluggable token stores (In-Memory, Redis, Dapr, ReaFx) |
| TLS Configuration | Custom CA and certificate trust configuration |
Getting Started
Package Installation
dotnet add package ProAuth.Oidc.Client
# Add a token store provider
dotnet add package ProAuth.Oidc.Client.InMemory # Development
dotnet add package ProAuth.Oidc.Client.Redis # ProductionBasic Setup
using ProAuth.Oidc.Client;
using ProAuth.Oidc.Client.InMemory;
var builder = WebApplication.CreateBuilder(args);
// Bind Authentication and add OIDC client services. This also validates
// that the removed Dpop:Enabled key is not present.
builder.Services.AddOidcClient(builder.Configuration, "Authentication");
// Add token store and locking
builder.Services.AddSingleton<ITokenStore, InMemoryTokenStore>();
builder.Services.AddSingleton<ILockProvider, InProcessLockProvider>();
// Add HTTP client factory
builder.Services.AddHttpClient();
var app = builder.Build();HTTP handler customization
Register transient DelegatingHandler implementations through the named IHttpClientFactory clients, after AddOidcClient (or after AddBff in a BFF application):
using Microsoft.Extensions.DependencyInjection;
using ProAuth.Oidc.Client;
services.AddOidcClient(configuration, "Authentication");
services.AddTransient<MyObserver>();
services.AddHttpClient("OidcClient")
.AddHttpMessageHandler<MyObserver>();
// Optional: observe discovery and JWT introspection signing-key retrieval too.
services.AddHttpClient(OidcDiscoveryClient.HttpClientName)
.AddHttpMessageHandler<MyObserver>();MyObserver can receive registered dependencies through its constructor. Multiple AddHttpMessageHandler calls execute in registration order on requests and reverse order on responses. For example, handlers A and B run A → B → transport → B → A. Client authentication and DPoP proofs are attached before the OidcClient pipeline runs, so observers also receive each response and any existing DPoP nonce retry. Do not add another DpopProofHandler to this named client.
| Integration point | Coverage |
|---|---|
"OidcClient" | IOidcClient form requests: token acquisition, authorization-code exchange, refresh, token exchange, device authorization, introspection, revocation and PAR. Includes automatic renewal through ITokenHandler. |
OidcDiscoveryClient.HttpClientName ("ProAuth.Oidc.Discovery") | OIDC client discovery and signing-key retrieval for JWT introspection. Cached metadata does not generate a request. |
ASP.NET Core OpenIdConnectOptions.BackchannelHttpHandler | Separate BFF middleware pipeline for interactive login discovery, code redemption, PAR and userinfo; see BFF customization. |
Handlers are pooled with the pipeline. Register a fresh handler per DI resolution, leave InnerHandler unset, and let the factory compose and dispose the chain. Dependencies resolve from the factory's handler scope, which is separate from an incoming request scope and can serve several requests concurrently. Do not store user-specific state in a handler or its scoped dependencies. Disposing a factory-created HttpClient does not dispose its pooled handlers. SetHandlerLifetime controls rotation; expired handlers and their scopes are disposed after clients release them. See the .NET factory lifetime guidance.
Primary transport and security
ProAuth configures both named protocol clients with AllowAutoRedirect = false and UseCookies = false. Applications do not need to inspect the concrete transport or traverse its handler chain to establish these defaults. Discovery, signing-key retrieval, PAR, code exchange, refresh, client credentials, device authorization/redemption, token exchange, introspection and revocation all use this policy.
Redirects, including same-origin redirects, are returned to protocol processing as unsuccessful responses; no request is sent to the redirect target. Configure direct endpoint URLs and proxies that return protocol responses directly. Transport redirects would run beneath request-specific client authentication and DPoP proof generation, potentially forwarding a form or proof without recalculating it for the new target. Set-Cookie responses are not stored in a transport cookie jar, and subsequent requests do not replay them. Existing bounded DPoP nonce retries remain enabled; these retry the original endpoint with a fresh proof.
ConfigurePrimaryHttpMessageHandler is honored for deliberate transport replacement. These two protocol clients require an HttpClientHandler or SocketsHttpHandler; ProAuth enforces both flags after normal named-client configuration, including on replacement transports. There is no supported redirect/cookie opt-in for these protocol clients. Use additional delegating handlers for observation and other middleware. An unsupported primary transport fails at client construction instead of bypassing the policy. Custom handlers must not follow redirects, retain/replay cookies, or introduce automatic retries of protocol requests.
Use the existing BFF TLS and authentication configuration for certificate trust and mTLS. The BFF supplies its configured TLS trust to both clients and its configured mTLS certificate only to "OidcClient". Ordinary HTTP client customization does not require transport access, for example:
services.AddHttpClient("OidcClient", client =>
client.Timeout = TimeSpan.FromSeconds(30));Replacing the primary transport replaces its TLS and client-certificate settings too; the application must supply the required trust and mTLS configuration. Standalone OIDC client applications continue to configure their own TLS/mTLS transport settings. Keep discovery free of token-endpoint credentials, authorization headers, client certificates and DPoP proofs. Issuer, HTTPS endpoint and discovery redirect validation remain in effect. Observation handlers must sanitize secrets, tokens, assertions and proofs before recording anything.
The BFF no longer replaces HttpMessageHandlerBuilder globally. Unrelated named clients therefore use their own transport and TLS settings. The legacy CustomHttpMessageHandlerBuilder type remains available for binary compatibility and now honors primary/additional handlers and the factory scope when activated through DI, but applications should remove manual registrations of it and use named-client configuration. Existing client names and authentication settings are unchanged.
Upgrade compatibility: Compared with 3.3.0, the package no longer follows protocol redirects or keeps transport cookies. Remove application patches that traverse or mutate ProAuth handler chains. Deployments relying on redirected endpoints or an upstream cookie session must return responses at the configured endpoints without those dependencies. This policy does not disable browser authorization/logout redirects or BFF application-session, correlation, nonce or antiforgery cookies.
Configuration
{
"Authentication": {
"Authority": "https://auth.example.com",
"ClientId": "my-service",
"ClientSecret": "service-secret",
"ClientAuthenticationMethod": "Auto",
"ServiceScopes": "openid api://my-api/.default",
"ServiceResources": "api://my-api"
}
}Discovery and issuer validation
Set Authority to the exact issuer identifier advertised by your provider. For example, https://idp.example.com/tenant-a loads https://idp.example.com/tenant-a/.well-known/openid-configuration. Nested paths are retained. A terminating slash is removed only when constructing the discovery URL; the returned issuer must still match the original Authority exactly, including case and trailing slash.
The client rejects discovery redirects, including redirects within the same origin. Configure the issuer and reverse proxy so the discovery URL returns its document directly. There is no fallback to host-root discovery and no issuer-mismatch bypass. Invalid metadata is not cached or used for subsequent token or signing-key requests.
The authority must be an absolute HTTPS URL without embedded credentials, query or fragment. Advertised protocol endpoint and signing-key URLs must use HTTPS without embedded credentials or fragments. Endpoint query parameters and other HTTPS origins are supported; endpoint URLs are supplied by the validated provider metadata. An endpoint is not required to share the issuer's hostname or tenant path. This client does not provide an endpoint-origin allowlist.
Discovery and signing-key retrieval for JWT introspection use the named HTTP client OidcDiscoveryClient.HttpClientName (ProAuth.Oidc.Discovery). Applications that configured certificate trust on the unnamed client or on the previous Discovery signing-key client must apply that trust to this named client or use ConfigureHttpClientDefaults before AddOidcClient. Keep automatic redirects disabled if replacing the discovery transport. The BFF's configured certificate trust continues to apply. Use trusted local certificates for development instead of disabling certificate validation.
Tenant routes advertising a root issuer
With UseTenantSpecificIssuerOnTenantSpecificEndpoints=false, a tenant discovery route advertises the root issuer. A tenant-path Authority will therefore fail validation. Enable tenant-specific issuers and configure the matching authority, or use the root authority with the appropriate tenant-routing configuration. Changing the issuer also affects token validation in consuming APIs; update their trusted issuer configuration together. See tenant issuer configuration.
Configuration Options
| Setting | Type | Description |
|---|---|---|
Authority | string | Exact HTTPS issuer identifier, including its tenant path and any advertised trailing slash |
ClientId | string | OAuth 2.0 client identifier |
ClientSecret | string | OAuth 2.0 client secret |
ClientAuthenticationMethod | string | Client authentication method for token, introspection, revocation, device authorization, and PAR requests. Supported values are Auto, None, ClientSecretPost, ClientSecretBasic, ClientSecretJwt, PrivateKeyJwt, TlsClientAuth, and SelfSignedTlsClientAuth. |
ClientAssertion | object | Settings for ClientSecretJwt and PrivateKeyJwt, including SigningAlgorithm, Certificate, CertificatePath, CertificatePassword, KeyId, and LifetimeInSeconds. |
MutualTls | object | Outbound client certificate settings for TlsClientAuth and SelfSignedTlsClientAuth, including Certificate, CertificatePath, and CertificatePassword. |
SecurityProfile | string | Set to Fapi2SecurityProfile to enable client-side FAPI 2.0 baseline checks. |
SenderConstrainedTokenMode | string | None, Dpop, or MutualTls. |
Dpop | object | RFC 9449 proof settings, including JsonWebKey, SigningAlgorithm, GenerateEphemeralKeyWhenMissing, RetryWithNonce, and ProofLifetimeInSeconds. |
PushedAuthorizationBehavior | string | PAR behavior: UseIfAvailable, Disable, or Require. |
RequestObject | object | RFC 9101 JAR settings for signed authorization request objects. |
AuthorizationRequestClaims | string | Raw OIDC claims request parameter JSON to add to authorization requests. |
JwtIntrospection | object | Enables RFC 9701 JWT introspection response validation. |
ServiceScopes | string | Space-separated scopes for client credentials flow |
ServiceResources | string | Space-separated resource identifiers |
UserScopes | string | Scopes for user authentication flows |
UserResources | string | Resources for user authentication flows |
With Fapi2SecurityProfile and PrivateKeyJwt, configure Authority as the exact authorization-server issuer identifier. Client assertions use this value as their scalar aud claim for all endpoint calls, including automatic refresh; the HTTP request still targets the discovered endpoint. Preserve the issuer path and trailing slash exactly; a missing or blank authority fails before an assertion is sent. This follows FAPI 2.0 section 5.3.3.1. The default profile retains endpoint audiences.
SenderConstrainedTokenMode is the only setting that activates DPoP. Remove Dpop:Enabled from existing configuration. The configuration-aware AddOidcClient overload rejects the removed key so an upgrade cannot silently disable DPoP.
Advanced Client Authentication
ProAuth.Oidc.Client applies the configured client authentication method to all client-authenticated OAuth endpoints it calls: token, introspection, revocation, device authorization, and PAR.
Explicit secret-based methods fail closed. ClientSecretPost, ClientSecretBasic, and ClientSecretJwt require ClientSecret; startup or request construction fails instead of silently downgrading to public-client authentication. Auto uses ClientSecretBasic when a secret is configured and None when no secret is configured.
Use ClientSecretJwt to sign assertions with the configured client secret:
{
"Authentication": {
"Authority": "https://auth.example.com",
"ClientId": "my-service",
"ClientSecret": "service-secret",
"ClientAuthenticationMethod": "ClientSecretJwt"
}
}Use PrivateKeyJwt when the matching public key is registered as a ClientAppKeySet on the ProAuth client app with usage ClientAssertionSigning:
{
"Authentication": {
"Authority": "https://auth.example.com",
"ClientId": "my-service",
"ClientAuthenticationMethod": "PrivateKeyJwt",
"ClientAssertion": {
"CertificatePath": "/var/run/secrets/proauth/client-assertion.pfx",
"CertificatePassword": "<pfx-password>",
"KeyId": "client-key-1"
}
}
}Use TlsClientAuth or SelfSignedTlsClientAuth when ProAuth expects an outbound client certificate:
{
"Authentication": {
"Authority": "https://auth.example.com",
"ClientId": "my-service",
"ClientAuthenticationMethod": "TlsClientAuth",
"MutualTls": {
"CertificatePath": "/var/run/secrets/proauth/mtls-client.pfx",
"CertificatePassword": "<pfx-password>"
}
}
}Advanced Authorization Security
For FAPI 2.0-style clients, configure PAR plus sender-constrained tokens:
{
"Authentication": {
"Authority": "https://auth.example.com",
"ClientId": "my-service",
"SecurityProfile": "Fapi2SecurityProfile",
"PushedAuthorizationBehavior": "Require",
"SenderConstrainedTokenMode": "Dpop",
"Dpop": {
"JsonWebKey": null,
"GenerateEphemeralKeyWhenMissing": true,
"RetryWithNonce": true
}
}
}The client library can add dpop_jkt to authorization requests, attach DPoP proofs to token endpoint calls, and retry once when ProAuth responds with a DPoP nonce challenge. For browser authorization requests, call PrepareAuthorizationRequest before building the redirect URL or before calling PAR. This applies configured OIDC claims, DPoP authorization binding, and JAR request objects.
var authRequest = oidcClient.PrepareAuthorizationRequest(new AuthRequest
{
ClientId = "my-service",
ResponseType = "code",
RedirectUri = "https://app.example.com/signin-oidc",
Scopes = new[] { "openid", "profile" },
State = state,
Nonce = nonce
});Enable RequestObject.Enabled to sign authorization parameters as a JWT request object. The request-object key can be supplied as base64 PFX certificate material or as a PFX file path through RequestObject.CertificateInput.
Use IntrospectTokenAsJwtAsync when ProAuth is configured to return RFC 9701 JWT introspection responses. The handler validates issuer, audience, signing keys, and configured token decryption keys before converting the JWT back to an introspection result.
Core Interfaces
IOidcClient
The IOidcClient interface provides direct access to OIDC protocol operations:
public interface IOidcClient
{
// Client credentials grant
Task<TokenResponse> ClientCredentialsAsync(
IEnumerable<string> scopes = null,
IEnumerable<string> resources = null,
CancellationToken cancellationToken = default);
// Refresh an access token
Task<TokenResponse> RefreshAccessTokenAsync(
string refreshToken,
IEnumerable<string> scopes = null,
IEnumerable<string> resources = null,
CancellationToken cancellationToken = default);
// Token exchange (RFC 8693)
Task<TokenResponse> ExchangeTokenAsync(
string subjectToken,
string subjectTokenType,
string requestedTokenType = null,
IEnumerable<string> scopes = null,
IEnumerable<string> resources = null,
string audience = null,
CancellationToken cancellationToken = default);
// Token introspection
Task<IntrospectionResponse> IntrospectTokenAsync(
string token,
string tokenTypeHint = null,
CancellationToken cancellationToken = default);
// Token revocation
Task<RevokeResponse> RevokeTokenAsync(
string token,
string tokenTypeHint = null,
CancellationToken cancellationToken = default);
}Token revocation
Call IOidcClient.RevokeTokenAsync(token, tokenTypeHint, cancellationToken) to revoke an access token or refresh token. The optional hint is access_token or refresh_token.
A successful HTTP 200 response returns an empty RevokeResponse. The client ignores the successful response body, including an empty body or non-JSON content, as specified by RFC 7009 section 2.2. An unknown or already invalid token also receives a successful response for an otherwise valid request; this acknowledgement does not prove that the token previously existed or that this request changed its state. Stop using the token after successful revocation.
HTTP/OAuth failures throw OidcErrorResponseException, which exposes the HTTP status and OAuth error information when available. Transport failures and cancellation propagate to the caller. Do not treat an exception as confirmation that the server revoked the token: a transport failure can leave the outcome uncertain, and HTTP 503 means the client must assume the token still exists.
Revocation acknowledgement and API enforcement are separate. APIs that introspect tokens can observe their inactive state, subject to propagation and any introspection caching. APIs validating self-contained JWTs locally can continue accepting them until expiry unless they perform an online status check or use another revocation mechanism. Token encryption and mTLS binding do not themselves provide such a check. See resource-server validation for introspection configuration.
ITokenHandler
The ITokenHandler interface provides high-level token management with automatic caching and refresh:
public interface ITokenHandler
{
// Get access token for a user (from token store)
Task<JwtSecurityToken> GetAccessTokenForUser(
string subjectIdentifier,
CancellationToken cancellationToken = default);
// Get access token for service-to-service calls
Task<JwtSecurityToken> GetAccessTokenForService(
CancellationToken cancellationToken = default);
}ITokenStore
The ITokenStore interface defines token persistence:
public interface ITokenStore
{
Task<UserTokens?> GetUserTokens(string subjectIdentifier, CancellationToken ct = default);
Task<ServiceTokens?> GetServiceTokens(string subjectIdentifier, CancellationToken ct = default);
Task StoreUserTokens(string subjectIdentifier, UserTokens userTokens, CancellationToken ct = default);
Task StoreServiceTokens(string subjectIdentifier, ServiceTokens serviceTokens, CancellationToken ct = default);
}Usage Examples
Client Credentials Flow
For service-to-service authentication:
public class MyBackendService
{
private readonly ITokenHandler _tokenHandler;
private readonly HttpClient _httpClient;
public MyBackendService(ITokenHandler tokenHandler, IHttpClientFactory httpClientFactory)
{
_tokenHandler = tokenHandler;
_httpClient = httpClientFactory.CreateClient();
}
public async Task<string> CallProtectedApiAsync()
{
// Get service access token (automatically cached and refreshed)
var token = await _tokenHandler.GetAccessTokenForService();
// Call protected API
_httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", token.RawData);
var response = await _httpClient.GetAsync("https://api.example.com/data");
return await response.Content.ReadAsStringAsync();
}
}Token Exchange
Exchange a user's token for a token with different scope/audience:
public class TokenExchangeService
{
private readonly IOidcClient _oidcClient;
public TokenExchangeService(IOidcClient oidcClient)
{
_oidcClient = oidcClient;
}
public async Task<string> ExchangeForDownstreamApiAsync(string userAccessToken)
{
var response = await _oidcClient.ExchangeTokenAsync(
subjectToken: userAccessToken,
subjectTokenType: "urn:ietf:params:oauth:token-type:access_token",
scopes: new[] { "api://downstream-api/.default" },
audience: "api://downstream-api");
if (response.IsError)
{
throw new InvalidOperationException($"Token exchange failed: {response.Error}");
}
return response.AccessToken;
}
}Token Introspection
Validate a token and get its claims:
public class TokenValidationService
{
private readonly IOidcClient _oidcClient;
public TokenValidationService(IOidcClient oidcClient)
{
_oidcClient = oidcClient;
}
public async Task<bool> ValidateTokenAsync(string token)
{
var response = await _oidcClient.IntrospectTokenAsync(
token: token,
tokenTypeHint: "access_token");
if (response.IsError)
{
return false;
}
return response.IsActive;
}
}Token Revocation
Revoke tokens when a user logs out:
public class LogoutService
{
private readonly IOidcClient _oidcClient;
public LogoutService(IOidcClient oidcClient)
{
_oidcClient = oidcClient;
}
public async Task RevokeUserTokensAsync(string accessToken, string refreshToken)
{
// Revoke refresh token first
if (!string.IsNullOrEmpty(refreshToken))
{
await _oidcClient.RevokeTokenAsync(refreshToken, "refresh_token");
}
// Revoke access token
if (!string.IsNullOrEmpty(accessToken))
{
await _oidcClient.RevokeTokenAsync(accessToken, "access_token");
}
}
}Token Store Providers
Refresh timing and retention
Three lifetimes serve different purposes:
- Refresh scheduling:
UserTokens.RefreshAttellsITokenHandlerwhen to attempt a refresh on the next token request. Tokens acquired by the handler normally use access-token expiry minus 30 seconds. This timestamp is not the refresh token's expiry, and there is no background refresh timer. - Access-token expiry: The provider's
expires_inand, for JWT access tokens,expdetermine how long an access token can be accepted. A retained expired access token must not be sent to an API; useITokenHandlerto obtain a usable token. - Session and store retention: The browser ticket lifetime or the standalone store's retention policy determines how long the application can retrieve credentials. The provider can independently expire or revoke the refresh grant. Keeping a refresh token locally does not guarantee that refresh will succeed.
The standalone in-memory store retains a user token set containing a refresh token past both RefreshAt and access-token expiry, until idle expiration or explicit removal. Passing the access-token boundary does not discard the refresh grant.
| Store | User-token retention | Service-token retention |
|---|---|---|
| In-memory | Sliding idle retention; successful reads extend it. Defaults to 60 minutes, or SessionIdleTimeout when supplied. With neither a refresh token nor a session timeout, RefreshAt is also an absolute cutoff. | Evicted at RefreshAt, or earlier after the configured idle period. Reads cannot extend the RefreshAt cutoff. |
| Redis | TTL set on each write: SessionIdleTimeout when supplied, otherwise until RefreshAt + 30 minutes. A nonpositive calculated TTL falls back to one hour. Reads do not extend the TTL. | TTL until RefreshAt + 30 minutes, with the same one-hour fallback. |
| Dapr / ReaFx | Standalone entries have no client-supplied TTL. Login entries with SessionIdleTimeout request a TTL of that timeout plus the remaining time until RefreshAt (if positive) plus 30 seconds, rounded up to whole seconds. Backend TTL support and configuration determine physical retention. Reads do not renew it. | No client-supplied TTL; backend policy or explicit removal determines retention. |
| Auth session | Tokens remain in the server-side browser ticket for its session lifetime; access-token expiry alone does not end that session. | Unsupported. Use a standalone store for client-credentials tokens. |
Service tokens contain no user refresh grant. When missing or due for renewal, ITokenHandler obtains a new token through client credentials. A distributed store may still return the old service entry after RefreshAt; the handler checks its schedule before reuse.
In-memory cleanup runs every five minutes by default, but reads also reject expired entries. Cleanup does not extend their idle lifetime. All in-memory credentials are lost on process restart. The backend differences above are intentional; changing providers can change how long an unused grant remains locally available.
Choosing browser-session or standalone storage
For an ASP.NET Core browser application, use WithAuthSessionTokenStore() with a server-side ticket store when tokens should belong to the browser login. The ticket is authoritative for session expiration, logout, refresh coordination and replacement after a new sign-in. Use a shared ticket store and distributed locking for multiple application instances.
The BFF also supports external in-memory, Redis, Dapr and ReaFx token stores. Its login-specific keys and session renewal/logout integration provide browser-session ownership around those stores. Storage TTL is a cleanup policy, not a replacement for validating the browser ticket.
Use a standalone store for service-to-service credentials or a custom flow that owns its credential lifetime independently of a browser ticket. Direct subject-keyed usage shares one entry for that key: it does not isolate two browser logins for the same subject. Applications must define their own key scope, retention and removal policy. For standalone user entries, coordinate replacement/removal with refresh using the same ILockProvider and TokenRefreshDefaults.UserLockKey(storeKey); raw ITokenStoreCleanup removal alone does not cancel an in-flight writer. Removing a cached service token does not disable subsequent client-credentials acquisition.
Step-up authentication also requires explicit session ownership. Reauthentication must update the intended login's tokens and verified assurance without overwriting another login for the same subject. Retention or silent refresh does not itself establish stronger authentication. See API authentication assurance and step-up.
In-Memory Store
Package: ProAuth.Oidc.Client.InMemory
services.AddSingleton<ITokenStore, InMemoryTokenStore>();
services.AddSingleton<ILockProvider, InProcessLockProvider>();Features:
- Automatic cleanup of expired tokens
- Configurable sliding expiration
- Thread-safe concurrent access
Configuration:
services.Configure<InMemoryTokenStoreOptions>(options =>
{
options.CleanupIntervalMinutes = 5;
options.TokenSlidingExpirationMinutes = 60;
});Redis Store
Package: ProAuth.Oidc.Client.Redis
services.AddSingleton<ITokenStore, RedisTokenStore>();
services.AddSingleton<ILockProvider, RedisLockProvider>();Configuration:
{
"Redis": {
"ConnectionString": "localhost:6379,password=secret,ssl=true"
}
}Dapr Store
Package: ProAuth.Oidc.Client.Dapr
services.AddSingleton<ITokenStore, DaprTokenStore>();
services.AddSingleton<ILockProvider, DaprLockProvider>();Requires Dapr state store component.
ReaFx Store
Package: ProAuth.Oidc.Client.ReaFx
services.AddSingleton<ITokenStore, ReaFxTokenStore>();
services.AddSingleton<ILockProvider, ReaFxLockProvider>();INFO
ReaFx integration requires a ReaFx license.
TLS Configuration
For environments with custom CAs or self-signed certificates:
services.Configure<TlsCertificateValidationConfiguration>(options =>
{
// Trust specific CA certificates
options.CustomTrustedRootCaFilePaths = new[]
{
"/etc/ssl/certs/custom-ca.crt"
};
// Or trust specific server certificates
options.CustomTrustedTlsCertificatePaths = new[]
{
"/etc/ssl/certs/auth-server.crt"
};
// Enable hot-reload of certificates
options.EnableFileSystemWatcher = true;
});DANGER
Never use AcceptAnyServerCertificates = true in production. This disables all certificate validation and exposes your application to man-in-the-middle attacks.
Error Handling
All protocol operations return response objects with error information:
var response = await _oidcClient.ClientCredentialsAsync();
if (response.IsError)
{
_logger.LogError(
"Token acquisition failed: {Error} - {Description}",
response.Error,
response.ErrorDescription);
throw new AuthenticationException(response.Error);
}
// Use response.AccessTokenThread Safety and Concurrency
The OIDC Client library is designed for concurrent use:
- Token caching: Tokens are cached and only refreshed when necessary
- Distributed locking: Token refresh operations use distributed locks to prevent race conditions
- Concurrent storage access: Built-in stores support concurrent operations; coordinate standalone replacement and removal with refresh as described in store selection.
Best Practices
Token Refresh Strategy
ITokenHandler checks RefreshAt when a token is requested and refreshes due user tokens or reacquires service tokens. The normal lead time is 30 seconds. Calling it again before RefreshAt returns the cached token; it does not force an early refresh.
Obtain a token close to each outbound request. For work that may outlive an access token, plan separate authenticated requests and handle authentication failures according to the operation's retry safety. Do not assume that a retained refresh grant extends an access token's validity or the browser session's lifetime.
Connection Resilience
Configure HTTP clients with retry policies:
services.AddHttpClient("OidcClient")
.AddPolicyHandler(GetRetryPolicy());
static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
{
return HttpPolicyExtensions
.HandleTransientHttpError()
.WaitAndRetryAsync(3, retryAttempt =>
TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
}Secure Secret Storage
Never store client secrets in source code:
// Use environment variables or secret management
var clientSecret = Environment.GetEnvironmentVariable("OIDC_CLIENT_SECRET")
?? throw new InvalidOperationException("Client secret not configured");See Also
- BFF (Backend-For-Frontend) - For browser-based applications
- Client Applications - Configure clients in ProAuth
- Token Exchange Configuration - Enable token exchange