Reference

ITraxPrincipalResolver

Package Trax.Api.AuthNamespace Trax.Api.AuthSource ITraxPrincipalResolver.cs

NO WARRANTY. Trax auth is plumbing, not a security product. You are solely responsible for securing systems that use it. See API Security.

Maps a credential to a TraxPrincipal. Generic over the input, so one abstraction serves every Trax scheme.

Signature

public interface ITraxPrincipalResolver<in TInput>
{
    ValueTask<TraxPrincipal?> ResolveAsync(TInput input, CancellationToken ct);
}

Parameters

ParameterTypeDescription
inputTInputThe credential, by scheme: see the table below.
ctCancellationTokenThe request's RequestAborted token.
SchemeTInputWhat the resolver receives
API keystringThe raw header value. The resolver decides whether it is valid.
JWT bearerJwtTokenInputThe token after JwtBearerHandler validated its signature, issuer, audience and lifetime: Principal (the token's claims) and SecurityToken.
OpenID ConnectOidcTokenInputThe sign-in after the OIDC handler validated the id-token: Principal, and IdToken and AccessToken as raw strings when the provider sent them.

Returns

The principal, or null when the input does not match a known principal. The scheme handler fails authentication on null.

Behavior

  • A resolver that throws fails authentication. The API-key handler logs the exception at Warning and fails with API-key resolver failed.; the JWT and OIDC handlers fail with the exception.
  • Lifetime, by registration:
RegistrationLifetime
AddTraxApiKeyAuth<TResolver>(), AddTraxJwtAuth<TResolver>(...), AddTraxOidcAuth<TResolver>(...)Scoped, resolved per request.
AddTraxApiKeyAuth(keys => ...)Singleton HashedApiKeyResolver over the configured keys, immutable once built.
AddTraxJwtAuth(...) without TResolverSingleton DefaultJwtPrincipalResolver.
AddTraxOidcAuth(...) without TResolverSingleton DefaultOidcPrincipalResolver.
  • On a GraphQL subscription the resolver is scoped per connection: the socket interceptor opens a scope when connection_init arrives and disposes it once the principal is resolved. See subscriptions.

Example

services.AddTraxJwtAuth<DirectoryJwtResolver>("https://login.example.com", "my-api");
 
public sealed class DirectoryJwtResolver(IUserDirectory users) : ITraxPrincipalResolver<JwtTokenInput>
{
    public async ValueTask<TraxPrincipal?> ResolveAsync(JwtTokenInput input, CancellationToken ct)
    {
        var sub = input.Principal.FindFirst("sub")?.Value;
        if (sub is null)
            return null;
 
        var user = await users.FindByIdAsync(sub, ct);
        if (user is null || user.IsRevoked)
            return null;
 
        return new TraxPrincipal(user.Id, user.DisplayName, user.Roles,
            Claims: new Dictionary<string, string> { ["tenant"] = user.TenantId },
            PrincipalType: JwtDefaults.PrincipalType);
    }
}

See also