ASP.NET Core Resource Server
ProAuth v3 includes ProAuth.Oidc.ResourceServer.AspNetCore for ASP.NET Core APIs that consume ProAuth access tokens. The package validates normal bearer JWTs and can additionally enforce sender-constrained access tokens, encrypted access tokens, and reference tokens.
Use this package for customer APIs that need the same resource-server behavior as the built-in Management API v2 and User Store API v2.
Package Setup
builder.Services.AddResourceServerAuthentication(
builder.Configuration,
options =>
{
options.Authority = "https://idp.example.com/";
options.Audience = "my-api";
options.AccessTokenPresentationPolicy = AccessTokenPresentationPolicy.BearerAndSenderConstrained;
});The authentication scheme name is Bearer, so existing ASP.NET Core [Authorize] policies and AuthenticationSchemes = "Bearer" continue to work.
Presentation Policies
| Policy | Behavior |
|---|---|
BearerOnly | Accepts unbound bearer tokens only. Tokens carrying a sender constraint and DPoP presentation are rejected. |
BearerAndSenderConstrained | Accepts unbound bearer tokens and also accepts DPoP or certificate-bound tokens when the required proof is present. This is the v3 default for ProAuth-owned APIs. |
SenderConstrainedRequired | Rejects unbound bearer tokens. DPoP-bound or certificate-bound tokens are accepted with proof. |
DpopRequired | Requires DPoP-bound access tokens and a valid DPoP proof header. |
CertificateBoundRequired | Requires an access token with cnf.x5t#S256 and a matching client certificate. |
In hybrid mode, a token that contains cnf.jkt cannot be used as plain bearer, and a token that contains cnf.x5t#S256 must match the caller certificate.
FAPI DPoP Algorithms
For an API protected by the FAPI 2.0 profile, restrict DPoP proofs to PS256 and ES256 as well as requiring sender-constrained tokens:
options.AccessTokenPresentationPolicy = AccessTokenPresentationPolicy.SenderConstrainedRequired;
options.Dpop.AllowedSigningAlgorithms = ["PS256", "ES256"];The same array can be configured at ResourceServer:Dpop:AllowedSigningAlgorithms. An omitted/null allowlist retains the package's generic asymmetric DPoP algorithms; an explicitly empty array rejects every algorithm. The restriction applies in addition to signature, token binding, request URI/method, lifetime and replay checks. APIs must also enforce their required scopes.
DPoP Replay Store
DPoP proof replay detection is mandatory. The package includes:
MemoryDpopProofReplayStorefor development and single-process APIs.- Optional
ProAuth.Oidc.ResourceServer.Redisfor atomic shared replay prevention across API replicas. IDpopProofReplayStorefor custom stores.
ReplayStore = DistributedCache and DistributedCacheDpopProofReplayStore deliberately reject use: IDistributedCache cannot atomically insert only when a key is absent. This remains true when its underlying provider is Redis. Use the dedicated replay package below, or supply an atomic custom store.
Redis Registration
Install ProAuth.Oidc.ResourceServer.Redis alongside the resource-server package at the same ProAuth version. Redis remains an optional dependency. Register one reusable StackExchange.Redis multiplexer per application, or reuse an existing singleton:
using ProAuth.Oidc.ResourceServer.AspNetCore;
using ProAuth.Oidc.ResourceServer.Redis;
using StackExchange.Redis;
builder.Services.AddSingleton<IConnectionMultiplexer>(_ =>
{
var connection = ConfigurationOptions.Parse(
builder.Configuration.GetConnectionString("DpopReplayRedis")!);
connection.AbortOnConnectFail = false;
connection.BacklogPolicy = BacklogPolicy.FailFast;
connection.AsyncTimeout = 3000;
return ConnectionMultiplexer.Connect(connection);
});
builder.Services.AddRedisDpopProofReplayStore(options =>
{
options.ApplicationName = "orders-api-production";
options.Issuer = "https://idp.example.com/tenant";
// options.Database = 0; // Default: the multiplexer's default database.
});
builder.Services.AddResourceServerAuthentication(builder.Configuration, options =>
{
options.Authority = "https://idp.example.com/tenant";
options.Audience = "orders-api";
options.AccessTokenPresentationPolicy = AccessTokenPresentationPolicy.DpopRequired;
options.Dpop.ReplayStore = DpopProofReplayStoreMode.Custom;
});The Redis extension selects the singleton replay store regardless of its order relative to AddResourceServerAuthentication. The connection's owner manages its lifetime; the store does not create or dispose connections per request. Store connection credentials securely and use authenticated TLS connections outside a trusted local test environment.
Identity, Isolation And Retention
Every replica must use the same Redis database, ApplicationName, Issuer, proof time window and request-path routing. ApplicationName identifies the logical application and environment, never a pod, deployment version or host instance. Issuer is an explicit trusted namespace, not an issuer-validation setting and is never taken from unvalidated request input. Configure token validation separately. Use distinct namespaces for independent application/issuer deployments.
There is one replay store and namespace per service provider, shared by its authentication schemes. For an API accepting multiple issuers, use one stable namespace for that entire trust domain on every replica. This conservatively shares replay identities across those issuers: matching client/key/proof/path tuples collide. Per-request issuer partitioning is not provided by this registration. Do not select different namespaces for requests that can accept the same proof.
Replay keys hash an unambiguous encoding of the namespace and the validator-supplied client identifier, key thumbprint, proof jti, and request path. Queries, access-token values, and authentication scheme names do not partition replay state. The validator checks method, public URI and access-token binding before registration. Changing a namespace or Redis database while proofs remain valid discards effective replay history.
Registration sends one SET with NX and an absolute expiration to the Redis primary; only one competing registration succeeds while the key exists. Expiration is the proof's iat + ProofTimeWindow, rounded up to millisecond precision. Accepted future-dated proofs can therefore require almost twice ProofTimeWindow of retention. Duplicate attempts do not extend retention. Expired inputs are rejected. See Redis SET semantics and DPoP replay considerations.
Redis Operations And Failure Limits
The supported restart setup uses a persistent /data volume and these Redis settings (Redis 6.2 or later is required for absolute SET expiry):
appendonly yes
appendfsync always
maxmemory-policy noevictionAOF on retained durable storage preserves unexpired replay keys through an ordinary graceful Redis restart. appendfsync always trades write latency for durability; snapshots alone or appendfsync everysec can lose recent accepted proofs after a failure. Test storage durability, backup/recovery procedures and shutdown behavior for your deployment. A successful restart test does not establish crash, disk-loss or failover guarantees. See Redis persistence.
- Eviction and capacity: replay state is security state. Use
noeviction, reserve capacity for peak proof rates over the full validation interval, and monitor rejected writes, persistence errors, memory and latency. Do not share an eviction-enabled cache, delete live keys, or runFLUSHDB/FLUSHALLagainst this database. Restrict administrative access. - Clocks: synchronize API replicas and Redis to UTC and monitor drift or clock steps. Redis evaluates absolute expiry using its clock; an ahead Redis clock or a behind validator clock can create a replay gap. The store adds no clock-skew allowance. All validators must agree on the time window; a longer-window replica can otherwise accept a proof after a shorter-window replica's entry expires.
- Unavailable or ambiguous storage: connection failures, timeouts, write rejection and cancellation prevent successful authentication. They propagate to the host; there is no memory fallback. Cancellation stops waiting but cannot recall a Redis command. A timed-out command may have consumed the proof, so retries need a fresh proof. Configure connection/command timeouts and host error handling without turning storage failures into authentication success.
- Failover and state loss: atomicity applies to a single authoritative Redis primary with retained state. Redis asynchronous replication can lose acknowledged writes during promotion; this implementation does not use
WAIT/WAITAOF, provide consensus, or prevent split-brain writes. Sentinel/Cluster routing does not strengthen that guarantee. See Redis replication limitations. - Recovery: the store cannot detect a healthy but empty or stale Redis database. On uncertain state loss, stop DPoP acceptance across all replicas, fence old writers, restore authoritative state or wait until every potentially lost proof is outside its validation interval before reopening. With a symmetric proof window, allow at least twice the largest configured window after the last possible acceptance, plus your clock uncertainty. Deployments requiring uninterrupted replay protection across partitions or lossy failover need a store with stronger consistency guarantees.
Reference And Encrypted Tokens
Local JWT validation verifies the token and its sender constraint but does not automatically observe server-side revocation before expiry. If the API needs immediate revocation awareness, configure online introspection with authentication supported by the issuer and enable Introspection.ValidateReadableTokens.
Readable JWT access tokens are validated locally. JWE access tokens are decrypted when decryption keys are configured. Opaque/reference tokens are resolved through IAccessTokenIntrospectionClient.
For standalone APIs, configure RFC 7662 introspection:
{
"ResourceServer": {
"Introspection": {
"Enabled": true,
"Endpoint": "https://idp.example.com/connect/introspect",
"ClientId": "api-introspection-client",
"ClientSecret": "<secret>"
}
}
}Signed introspection responses
Configure response trust using Introspection.JwtResponse. No TokenValidationParameters or custom lifetime validator is needed:
builder.Services.AddResourceServerAuthentication(builder.Configuration, options =>
{
options.Authority = "https://idp.example.com";
options.Audience = "my-api"; // Access-token audience, separate from the response recipient.
options.Introspection.Enabled = true;
options.Introspection.Endpoint = "https://idp.example.com/connect/introspect";
options.Introspection.ClientId = "api-introspection-client";
options.Introspection.ClientSecret = introspectionClientSecret; // Load from your secret store.
options.Introspection.JwtResponse.Issuer = "https://idp.example.com";
options.Introspection.JwtResponse.Audience = "api-introspection-client";
options.Introspection.JwtResponse.SigningKeys = [trustedAuthorizationServerSigningKey];
});trustedAuthorizationServerSigningKey is a Microsoft.IdentityModel.Tokens.SecurityKey obtained from the trusted issuer's signing-key configuration or JWKS. Configure key rotation as appropriate for your deployment; the HTTP introspection client does not automatically discover or refresh keys. For signed and encrypted responses, also set Introspection.JwtResponse.DecryptionKeys to the resource server's private decryption keys. The decrypted inner JWT must pass the same signature and envelope checks.
Set the response audience to the recipient identifier used by your authorization server. ProAuth uses the introspecting client's ID. It is not inferred from options.Audience or Introspection.ClientId. The issuer must match exactly, including any trailing slash; when JwtResponse.Issuer and advanced issuer settings are absent, Authority supplies the expected response issuer without normalization.
The package follows RFC 9701 section 5: it verifies the signature, issuer, response audience, and token-introspection+jwt type (including its full application/ form). The envelope must contain iss, aud, numeric iat, and an object-valued token_introspection with a boolean active. A signed response cannot fall back to top-level introspection members. Standard nested claims must have their protocol-defined JSON types. An inactive response contains only active: false and yields no authenticated principal.
Response freshness and clock skew
RFC 9701 recommends omitting envelope exp. The package accepts that form and limits response age using envelope iat:
| Option | Default | Meaning |
|---|---|---|
Introspection.JwtResponse.MaxAge | One minute | Positive maximum response age before clock-skew tolerance. |
Introspection.JwtResponse.ClockSkew | Five seconds | Nonnegative tolerance for response timestamps. |
These defaults are package policy, not RFC requirements: a one-minute age limit bounds response reuse while allowing ordinary request delays, and five seconds allows modest clock differences. Keep the authorization server and resource server clocks synchronized. A response is accepted only when now - MaxAge - ClockSkew <= iat <= now + ClockSkew. With the defaults, its maximum effective age is 65 seconds. A stricter application policy can use:
options.Introspection.JwtResponse.MaxAge = TimeSpan.FromSeconds(30);
options.Introspection.JwtResponse.ClockSkew = TimeSpan.FromSeconds(5);If envelope exp or nbf is supplied, it must be a numeric date: now < exp + ClockSkew and nbf <= now + ClockSkew. Expiration must follow iat, and nbf must not exceed exp. Missing, malformed, stale, or excessively future iat fails validation even if exp is valid. Timestamp checks use the injected TimeProvider when registered, otherwise the system UTC clock.
Envelope freshness is independent of the access token's lifetime. Only nested introspection claims become the authenticated principal. Nested iat, nbf, and exp describe the access token and do not extend or shorten the response freshness window. For opaque tokens, the authorization server's active decision remains authoritative. Readable access tokens still undergo local issuer, audience, signature, and lifetime validation before optional online introspection; a fresh response cannot rescue an expired access token.
Compatibility and migration
PreferJwtResponse retains its existing meaning: its default of true adds Accept: application/token-introspection+jwt; false omits that preference. It is not a requirement that the server return JWT. Plain JSON responses remain supported, and JWT responses are validated regardless of this preference. Configure server-side response policy if your deployment requires signed responses.
Existing JwtResponseValidationParameters issuer/audience settings, signing-key resolvers, algorithm restrictions, decryption keys, and validation delegates remain available for advanced integrations. The package clones these parameters. Explicit JwtResponse trust/key properties replace the corresponding static parameter settings. Issuer, audience, signature, type, structure, and freshness checks remain mandatory; disabling legacy validation flags does not disable the response profile. An explicit lifetime validator runs as an additional restriction and can reject a response, but cannot bypass the profile. The package removes the generic requirement for exp and uses JwtResponse.MaxAge/ClockSkew for envelope time checks; legacy TokenValidationParameters.ClockSkew still applies to any other IdentityModel checks or custom delegates that use it. Remove protocol-specific lifetime workarounds when migrating.
Following RFC 9701 section 8.1, introspection responses cannot be presented as access tokens. Local access-token validation accepts at+jwt, JWT, and their application/ forms by default. Existing explicit access-token type customization remains available through TokenValidationParameters, but a token marked as an introspection response or carrying token_introspection is always rejected on the access-token path.
ProAuth API Defaults
Management API v2 and User Store API v2 use:
{
"ResourceServer": {
"AccessTokenPresentationPolicy": "BearerAndSenderConstrained",
"Dpop": {
"ProofTimeWindow": "00:05:00",
"ReplayStore": "Custom"
},
"Introspection": {
"Enabled": true
},
"TokenDecryption": {
"Enabled": true
}
}
}This preserves existing bearer-token integrations while allowing ProAuth-owned clients and upgraded customer clients to use DPoP or certificate-bound tokens.
Migration Path
- Deploy APIs in
BearerAndSenderConstrained. - Enable FAPI 2.0 and DPoP for the Admin App/BFF with a persistent DPoP private JWK.
- Enable DPoP for CLI profiles with
proauthcli login --dpoporproauthcli loginservice --dpop. - Move customer integrations to the ProAuth client libraries or to another DPoP-capable client.
- Change API policy to
SenderConstrainedRequiredorDpopRequiredonly after legacy integrations have migrated.
Use BearerOnly when an older environment cannot yet send DPoP proofs or client certificates.
Downstream token exchange
After successful authentication and endpoint authorization, HttpContext.GetValidatedAccessToken() (namespace ProAuth.Oidc.ResourceServer.AspNetCore.Authentication) retrieves the original token for an authorized exchange. It throws when no validated token exists for the selected scheme. Use the receiving API’s own credentials and proof key with IOidcClient.ExchangeTokenAsync; never forward the incoming DPoP proof. See token exchange configuration for policy registration and trust responsibilities.
API authentication assurance
See API authentication assurance and step-up for opt-in client policies, verified token evidence, RFC 9470 challenges and bounded BFF reauthentication.