Added in Unreleased.
ZeeKayDa.Auth exposes several extension points you can implement to plug in custom behaviour at the scope catalog, client storage, secret hashing, and authentication layers:
IScopeRepository— supplies the scopes the authorization server knows about, e.g. from a database, a remote config service, or a per-tenant store.IClientRepository— supplies client registrations at request time, e.g. from a relational database or a multi-tenant store.IClientSecretHasher— plugs in a custom hashing algorithm (bcrypt, Argon2, etc.) or supports credential migration.IClientAuthenticator— adds a new token-endpoint authentication method beyondclient_secret_basicandclient_secret_post.
The repository interfaces are fully asynchronous and cancellation-aware. This guide shows you how to implement each extension point correctly. The scope signature looks like this:
public interface IScopeRepository
{
Task<IReadOnlyCollection<ScopeDefinition>> GetScopesAsync(CancellationToken cancellationToken = default);
}
Why the repository interfaces are async
The scope and client repositories sit on a hot request path: every discovery, authorize and token request reaches them. Real-world implementations are almost always I/O-bound — a database query, an HTTP call, a distributed cache lookup. Forcing those implementations to block a thread-pool thread is the well-known sync-over-async foot-gun: under load it causes thread-pool starvation, and it makes it impossible to honour request cancellation cleanly.
Every asynchronous extension point returns Task or Task<T>, never ValueTask: a Task can be awaited more than once and stored without surprises. An implementation that completes synchronously returns Task.FromResult(value) or Task.CompletedTask.
1. Implement a custom scope repository
A minimal database-backed example. Note that the CancellationToken is propagated through to the database call so the operation can be cancelled by the client.
public sealed class DatabaseScopeRepository : IScopeRepository
{
private readonly IDbContextFactory<ScopeDbContext> _factory;
public DatabaseScopeRepository(IDbContextFactory<ScopeDbContext> factory)
=> _factory = factory;
public async Task<IReadOnlyCollection<ScopeDefinition>> GetScopesAsync(
CancellationToken cancellationToken = default)
{
await using var db = await _factory.CreateDbContextAsync(cancellationToken);
var rows = await db.Scopes
.AsNoTracking()
.ToListAsync(cancellationToken);
return rows
.Select(row => new ScopeDefinition
{
Name = row.Name,
IsDiscoverable = row.IsDiscoverable,
IdTokenClaims = row.IdTokenClaims,
AccessTokenClaims = row.AccessTokenClaims,
})
.ToArray();
}
}
Register the repository on the ZeeKayDaAuthBuilder returned by AddZeeKayDaAuth:
builder.Services.AddZeeKayDaAuth(options => options.Issuer = "https://id.example.com");
builder.Services.AddDbContextFactory<ScopeDbContext>(/* ... */);
builder.Services.AddSingleton<IScopeRepository, DatabaseScopeRepository>();
2. Honour the cancellation token
The framework passes HttpContext.RequestAborted to your implementation. You should:
- Pass the token through to every async call you make (HTTP client, database, cache).
- Call
cancellationToken.ThrowIfCancellationRequested()at the start of synchronous in-memory implementations so a cancelled request doesn’t waste work building a response that will be discarded. - Never silently swallow
OperationCanceledException. Let it propagate — the framework treats it as a client disconnect and stops the request pipeline cleanly.
The in-tree InMemoryScopeRepository demonstrates the minimum pattern for synchronous in-memory implementations:
public Task<IReadOnlyCollection<ScopeDefinition>> GetScopesAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.FromResult(_scopes);
}
⚠ Do not “sync over async”
If you only have a synchronous data source today and are tempted to wrap it like this — don’t:
// ❌ Don't do this.
public Task<IReadOnlyCollection<ScopeDefinition>> GetScopesAsync(CancellationToken cancellationToken = default)
=> Task.FromResult<IReadOnlyCollection<ScopeDefinition>>(LoadFromHttpClientSync());
private IReadOnlyCollection<ScopeDefinition> LoadFromHttpClientSync()
=> _httpClient.GetAsync("/scopes").Result.Content.ReadFromJsonAsync<ScopeDto[]>().Result;
.Result and .GetAwaiter().GetResult() block a thread-pool thread for the duration of the I/O. Under load, every concurrent discovery request consumes a thread until the I/O completes, and the thread pool runs out — the symptom is rising request latency and eventually deadlocks under SynchronizationContext-bearing hosts.
If your data source has only a synchronous API, the right answer is to put a real cache (IMemoryCache, HybridCache, IDistributedCache) in front of it and refresh the cache from a background IHostedService — then your GetScopesAsync returns Task.FromResult(_cached) and you have not introduced sync-over-async on the hot path.
3. Implement a custom client secret hasher
ZeeKayDa.Auth ships with a PBKDF2-HMAC-SHA256 hasher (Pbkdf2ClientSecretHasher) that covers the vast majority of deployments. If you need a different hashing algorithm — for example during a migration from an existing bcrypt or Argon2 credential store — you can plug in a custom hasher by following the four-step pattern below.
Step 1: Define a sub-interface of IClientSecret
The C# type of the credential identifies which hasher handles it — no string discriminator is needed. Define a public interface that carries the fields your algorithm needs:
using ZeeKayDa.Auth.Clients;
public interface IBcryptClientSecret : IClientSecret
{
string Hash { get; }
}
Step 2: Define a sealed record implementing the interface
Every credential implements IClientCredential.Snapshot(). When the framework looks a client up, it validates a copy of the registration and authenticates the client against that same copy, so each credential must return a new instance that shares no mutable state with itself. A string cannot change, so this record can share it — but it still returns a new instance, because the framework rejects a credential whose Snapshot() returns itself or null (client.credentials.not_copied). A credential holding a byte[] must copy the array.
public sealed record BcryptClientSecret(string Hash) : IBcryptClientSecret
{
public IClientCredential Snapshot() => this with { };
}
If store entities implement your sub-interface directly, declare the copy on the sub-interface instead, as the built-in IPbkdf2ClientSecret does, so no entity has to write one:
public interface IBcryptClientSecret : IClientSecret
{
string Hash { get; }
IClientCredential IClientCredential.Snapshot() => new BcryptClientSecret(Hash);
}
Step 3: Subclass ClientSecretHasher<TSecret>
ClientSecretHasher<TSecret> handles all cross-cutting concerns (type dispatch, exception swallowing, null/whitespace rejection). You only need to implement VerifyCore and CreateCore:
using System.Security.Cryptography;
using ZeeKayDa.Auth.Clients;
// using BCrypt.Net; // replace with your chosen hashing library
public sealed class BcryptClientSecretHasher : ClientSecretHasher<IBcryptClientSecret>
{
protected override bool VerifyCore(IBcryptClientSecret stored, ReadOnlySpan<char> presented)
{
if (presented.IsEmpty)
return false;
// Use your library's built-in constant-time verify function.
// If the library accepts a string, allocate here with presented.ToString().
return BCrypt.Net.BCrypt.Verify(presented.ToString(), stored.Hash);
}
protected override IBcryptClientSecret CreateCore(string plaintext)
{
string hash = BCrypt.Net.BCrypt.HashPassword(plaintext, workFactor: 12);
return new BcryptClientSecret(hash);
}
}
⚠️ Warning: override
CreateCore(ReadOnlySpan<char>)to preserve the memory-safety guarantee. The primaryIClientSecretHasher.Createoverload acceptsReadOnlySpan<char>so callers can zero theirchar[]buffer immediately after the call. If you only overrideCreateCore(string), the base-class fallback allocatesnew string(plaintext)and delegates to it — the caller zeros their buffer, but a full managed string copy of the secret remains on the heap until the next GC cycle.Most .NET crypto primitives accept a span directly, so the override is usually a one-liner:
protected override IBcryptClientSecret CreateCore(ReadOnlySpan<char> plaintext) { // BCrypt.Net requires a string; the ToString() allocation here is intentional and bounded. string hash = BCrypt.Net.BCrypt.HashPassword(plaintext.ToString(), workFactor: 12); return new BcryptClientSecret(hash); }Algorithms whose .NET API accepts a span natively (e.g.
Rfc2898DeriveBytes.Pbkdf2,SHA256.HashData,HMACSHA256.HashData) can avoid theToString()entirely. SeePbkdf2ClientSecretHasherin the source for a complete example.
Step 4: Register with AddClientSecretHasher<T>()
Register your hasher on the builder returned by AddZeeKayDaAuth. The composite verifier tries the matching hasher for each stored credential. The built-in PBKDF2 hasher is always registered and, unless you mark another hasher as the default, creates every new secret. To keep verifying secrets hashed with another algorithm, register that hasher alongside it; to make your own hasher create new secrets, mark it isDefault: true — PBKDF2 stays registered, so existing PBKDF2 secrets keep verifying:
auth.AddClientSecretHasher<BcryptClientSecretHasher>(); // verifies old bcrypt secrets
// or
auth.AddClientSecretHasher<BcryptClientSecretHasher>(isDefault: true); // also creates new secrets
Every registered hasher’s Create runs once at startup to build its timing decoy, so a hasher that only verifies legacy secrets must still create one for a random value.
Security contract for VerifyCore implementors
| Requirement | Reason |
|---|---|
| Use timing-safe comparison | Prevents timing oracles from revealing whether a client exists |
Never throw — return false on error | ClientSecretHasher<T> swallows exceptions, but throwing leaks timing |
Never log presented | Logging a plaintext secret violates confidentiality |
| Be singleton-safe | Hashers are registered as singletons and called concurrently |
Warning: A hasher that does not use constant-time comparison undermines the timing protections built into the framework. Use
CryptographicOperations.FixedTimeEqualsfor raw byte comparisons, or your library’s built-in constant-time verify function.
💡 Exception messages are now redacted by default.
SanitizingLoggerunconditionally wraps all logged exceptions inRedactedExceptionWrapper, replacing the exceptionMessagewith a fixed placeholder before it reaches any log sink. You no longer need to avoid putting credential material in exception messages as a workaround — though doing so remains good practice. To restore original exception messages in a development environment, callDisableExceptionSanitizing()on the builder. See Configure host-level log hygiene for details.
⚠️ Warning:
SanitizingLoggercovers ZeeKayDa.Auth’s own logs only. The redaction wrapper intercepts log calls made by ZeeKayDa.Auth’s internal services. It has no effect on ASP.NET Core’sUseHttpLogging(), Kestrel connection logging, W3CLogger, Application Insights telemetry, or exception-handling middleware — all of which can capture theAuthorizationheader or a form-encodedclient_secretentirely outside the library’s scope.See Configure host-level log hygiene for the steps required to close this gap in the host pipeline.
4. Implement a custom client repository
A custom IClientRepository is the right approach when your client registrations live outside the in-memory defaults — for example in a relational database, a multi-tenant store, or an external configuration service. The interface has a single read method:
public interface IClientRepository
{
Task<IClientRegistration?> FindByClientIdAsync(
string clientId, CancellationToken cancellationToken = default);
}
Startup path vs. runtime admin path
| Scenario | Recommended approach |
|---|---|
| Clients known at startup | AddInMemoryClients — the builder hashes secrets automatically |
| Clients created at runtime (admin API, credential rotation, future RFC 7591 DCR) | Custom IClientRepository + inject ClientSecrets |
Using ClientSecrets to hash secrets at write time
Inject ClientSecrets into your repository to hash plaintext secrets at runtime using the same default hasher configured via AddClientSecretHasher<T>. ClientSecrets is registered automatically by AddZeeKayDaAuth as a singleton — no additional registration is required.
public sealed class DatabaseClientRepository : IClientRepository
{
private readonly IDbContextFactory<ClientDbContext> _factory;
private readonly ClientSecrets _secrets;
private readonly ClientRegistrationValidator _validator;
public DatabaseClientRepository(
IDbContextFactory<ClientDbContext> factory,
ClientSecrets secrets,
ClientRegistrationValidator validator)
{
_factory = factory;
_secrets = secrets;
_validator = validator;
}
public async Task<IClientRegistration?> FindByClientIdAsync(
string clientId, CancellationToken cancellationToken = default)
{
await using var db = await _factory.CreateDbContextAsync(cancellationToken);
var row = await db.Clients.FindAsync([clientId], cancellationToken);
return row is null ? null : MapToRegistration(row);
}
public async Task RegisterClientAsync(string clientId, string plaintextSecret)
{
ClientSecret credential = _secrets.Create(plaintextSecret);
// Refuse the write if _validator.Validate(registration) returns any failures...
}
}
Validate before persisting
A custom repository should call ClientRegistrationValidator.Validate before writing a new or updated client registration to the store. The validator enforces the same startup-time rules that apply to in-memory clients — required fields, allowed grant types, consistent redirect URI configuration, and so on. Skipping validation does not let a malformed registration reach the protocol — the framework validates every registration it serves and refuses a failing one as an unknown client — but it does mean the bad row is stored, and is found on a live request, in a log entry the operator has to act on, rather than where it was written.
⚠️ Warning:
ClientSecrets.Createis CPU-intensive and must not be called on a hot request path. At the default iteration count of 600,000 PBKDF2-HMAC-SHA256 rounds, a single call takes approximately 600 ms on typical server hardware. Calling it from a token-endpoint handler or any other frequently-hit path will degrade throughput for all clients on the server.Reserve
ClientSecrets.Createfor admin operations only. The endpoint that calls it MUST be protected by strong authentication, rate-limited to prevent brute-force amplification, and logged for audit purposes.
Registration
builder.Services.AddSingleton<IClientRepository, DatabaseClientRepository>();
For the full ClientSecrets API reference, including lifetime and security notes, see Client secrets reference — ClientSecrets.
5. Implement a custom client authenticator
IClientAuthenticator lets you plug a new token endpoint authentication method into the framework’s dispatch pipeline. The built-in ClientSecretAuthenticator handles client_secret_basic and client_secret_post; everything else requires a custom implementation.
⚠️
CanHandlemust be a cheap shape check. Do not perform crypto operations, database lookups, or any I/O inCanHandle. It is called for every registered authenticator on every token-endpoint request. A slowCanHandlemultiplies across all registered authenticators and degrades every token-endpoint hit — not just requests for your authentication method.Parse a header, check a form key, or inspect a connection property. Do not call a database, validate a signature, or make an HTTP request.
Note:
noneis a special case — it is handled automatically by the composite dispatcher as a fallback for public clients and does not require anIClientAuthenticatorimplementation. The server advertises it by default, so registering a public client is all that is needed.
The interface has three members:
public interface IClientAuthenticator
{
IReadOnlySet<string> AuthenticationMethods { get; }
ClientAuthenticatorMatch CanHandle(TokenRequestContext context);
Task<ClientAuthenticationResult> AuthenticateAsync(
ClientAuthenticationContext context,
CancellationToken cancellationToken);
}
Step 1: Define the authentication method string
Use the registered string for your method (e.g. "private_key_jwt"). Declare it as a constant so AuthenticationMethods and CanHandle always return the same value:
public sealed class PrivateKeyJwtAuthenticator : IClientAuthenticator
{
private const string Method = "private_key_jwt";
private static readonly IReadOnlySet<string> _methods =
new HashSet<string>(StringComparer.Ordinal) { Method };
public IReadOnlySet<string> AuthenticationMethods => _methods;
Step 2: Implement CanHandle — keep it cheap
CanHandle is called for every token request, on every registered authenticator, before any repository lookup. It MUST be a cheap shape check — no crypto, no database access.
public ClientAuthenticatorMatch CanHandle(TokenRequestContext context)
{
// Shape check only: does the request carry any of this method's parameters?
var hasAssertion = context.Form.ContainsKey("client_assertion");
var hasType = context.Form.ContainsKey("client_assertion_type");
if (!hasAssertion && !hasType)
return ClientAuthenticatorMatch.None;
// Your shape, but partial or malformed: refuse. Never answer None here, or the request falls
// through to the `none` method and a public client is accepted with the assertion ignored.
return hasAssertion &&
context.Form["client_assertion_type"] == "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
? ClientAuthenticatorMatch.For(Method)
: ClientAuthenticatorMatch.Refused;
}
A slow CanHandle adds latency proportional to the number of registered authenticators on every token request — not just for your method, but for every client. Parse a header or check a form key; do not call a database or validate a signature here.
Step 3: Implement AuthenticateAsync
AuthenticateAsync is only invoked after CanHandle matched a method and all composite allowlist checks have passed. The matched method is context.Method, and the client is guaranteed to exist in the repository.
public Task<ClientAuthenticationResult> AuthenticateAsync(
ClientAuthenticationContext context,
CancellationToken cancellationToken)
{
var assertion = context.Form["client_assertion"].ToString();
// Validate the JWT assertion against the client's registered public key.
var valid = ValidateAssertion(assertion, context.Client, context.ClientId);
return Task.FromResult(
valid ? ClientAuthenticationResult.Valid() : ClientAuthenticationResult.NotValid());
}
Step 4: Register the authenticator
Register on the ZeeKayDaAuthBuilder returned by AddZeeKayDaAuth. The methods it declares in AuthenticationMethods are advertised and accepted from then on, unless TokenEndpoint.AdvertisedAuthMethods withholds them:
builder.Services.AddZeeKayDaAuth(options => options.Issuer = "https://id.example.com")
.AddClientAuthenticator<PrivateKeyJwtAuthenticator>();
Security contract for IClientAuthenticator implementors
| Requirement | Reason |
|---|---|
CanHandle MUST be a cheap shape check — no crypto, no DB | Called on every token request for every authenticator; a slow check multiplies latency across all clients |
AuthenticateAsync MUST use timing-safe comparison | Prevents timing oracles from revealing credential validity |
| Never compare secrets as plain strings or call a hasher yourself | Check a client secret with ClientSecrets.Verify, which pads a failure so the response time reveals nothing; a hasher called directly does not |
| Be singleton-safe | Authenticators are registered as singletons and called concurrently |
Refuse with ClientAuthenticationResult.NotValid() when no secret was checked — never throw | Throwing from AuthenticateAsync produces a 500 rather than a 401; the token endpoint pads a NotValid() refusal so it takes as long as a wrong secret |
A client secret is checked with ClientSecrets.Verify and returned with ClientAuthenticationResult.From(...) | Verify has already padded the failure; From tells the token endpoint not to pad it twice |
💡 Exception messages are now redacted by default.
SanitizingLoggerunconditionally wraps all logged exceptions inRedactedExceptionWrapper, replacing the exceptionMessagewith a fixed placeholder before it reaches any log sink. You no longer need to avoid putting credential material in exception messages as a workaround — though doing so remains good practice. To restore original exception messages in a development environment, callDisableExceptionSanitizing()on the builder. See Configure host-level log hygiene for details.
⚠️ Warning:
SanitizingLoggercovers ZeeKayDa.Auth’s own logs only. The redaction wrapper intercepts log calls made by ZeeKayDa.Auth’s internal services. It has no effect on ASP.NET Core’sUseHttpLogging(), Kestrel connection logging, W3CLogger, Application Insights telemetry, or exception-handling middleware — all of which can capture theAuthorizationheader or a form-encodedclient_secretentirely outside the library’s scope.See Configure host-level log hygiene for the steps required to close this gap in the host pipeline.
See also
- Configure ZeeKayDa.Auth — register the framework and the minimum required options.
- Configure discovery — customise the discovery document with the built-in options.
- Configure host-level log hygiene — prevent sensitive parameters from appearing in host-pipeline logs outside ZeeKayDa.Auth’s redaction boundary.
AuthorizationServerOptionsreference — full property list and validation rules.- Client secrets reference —
Pbkdf2ClientSecretHasherOptionsproperty reference andClientSecretsAPI. - Cancellation in managed threads — Microsoft’s reference for the cancellation pattern this framework follows.