Configuration Reference
Overview
Section titled “Overview”The AuthrimServerConfig object configures token validation, JWKS fetching, DPoP support, and provider implementations. This page documents every configuration field, the provider system, and runtime-specific considerations.
AuthrimServerConfig Reference
Section titled “AuthrimServerConfig Reference”Required Fields
Section titled “Required Fields”| Field | Type | Description |
|---|---|---|
issuer | string | string[] | Expected token issuer (iss claim). Must match the Authorization Server’s issuer URL |
audience | string | string[] | Expected token audience (aud claim). Your Resource Server identifier |
Optional Fields
Section titled “Optional Fields”| Field | Type | Default | Description |
|---|---|---|---|
jwksUri | string | OIDC discovery | JWKS endpoint URL. When multiple issuers are configured, this shared URI is used for all issuers |
jwksUriByIssuer | Record<string, string> | {} | Issuer-specific JWKS endpoints. Only configured issuers are accepted |
dynamicJwksDiscovery | boolean | true | Discover JWKS from each allowed issuer’s OpenID Configuration when no explicit URI is configured |
jwksRefreshIntervalMs | number | 3600000 (1 hour) | JWKS cache TTL / refresh interval in milliseconds |
clockToleranceSeconds | number | 60 | Clock skew tolerance for exp/nbf/iat checks |
introspectionEndpoint | string | undefined | Shared token introspection endpoint |
introspectionEndpointByIssuer | Record<string, string> | {} | Issuer-specific introspection endpoints |
revocationEndpoint | string | undefined | Shared token revocation endpoint |
revocationEndpointByIssuer | Record<string, string> | {} | Issuer-specific token revocation endpoints |
stepUpEndpoint | string | {issuer}/auth/step-up | Shared canonical Step-Up endpoint base |
stepUpEndpointByIssuer | Record<string, string> | {} | Issuer-specific Step-Up endpoint bases |
clientCredentials | { clientId: string; clientSecret: string } | undefined | Client credentials for introspection and revocation |
tokenValidation | Omit<TokenValidationOptions, 'issuer' | 'audience'> | {} | Additional validation rules such as scopes and tenant policy |
http | HttpProvider | fetchHttpProvider() | HTTP provider for network requests |
crypto | CryptoProvider | webCryptoProvider() | Cryptographic operations provider |
clock | ClockProvider | systemClock() | Clock provider for time-based checks |
jwksCache | CacheProvider<CachedJwk[]> | memoryCache() | Cache provider for JWKS data |
requireHttps | boolean | true | Require HTTPS for issuer and security-critical endpoint URLs |
Minimal Configuration
Section titled “Minimal Configuration”The simplest setup requires only issuer and audience:
import { createAuthrimServer } from '@authrim/server';
const server = createAuthrimServer({ issuer: 'https://auth.example.com', audience: 'https://api.example.com',});This uses all defaults: dynamic JWKS discovery from the issuer’s OpenID Configuration, a 1-hour in-memory JWKS cache, 60 seconds of clock tolerance, HTTPS enforcement, and the Web Crypto API.
Full Configuration Example
Section titled “Full Configuration Example”import { createAuthrimServer } from '@authrim/server';import { fetchHttpProvider, webCryptoProvider, systemClock, memoryCache,} from '@authrim/server/providers';
const server = createAuthrimServer({ // Required issuer: [ 'https://auth.example.com', 'https://auth.partner.example', ], audience: 'https://api.example.com',
// JWT validation and tenant policy clockToleranceSeconds: 30, tokenValidation: { requiredScopes: ['profile:read'], tenantClaim: 'tenant_id', allowedTenantIds: ['tenant_prod'], },
// JWKS. You can also omit these and use dynamic discovery. jwksUriByIssuer: { 'https://auth.example.com': 'https://auth.example.com/.well-known/jwks.json', 'https://auth.partner.example': 'https://auth.partner.example/.well-known/jwks.json', }, jwksRefreshIntervalMs: 3600000, // 1 hour
// Canonical Step-Up endpoint override. Defaults to {issuer}/auth/step-up. stepUpEndpointByIssuer: { 'https://auth.example.com': 'https://auth.example.com/auth/step-up', },
// Token introspection and revocation introspectionEndpoint: 'https://auth.example.com/oauth/introspect', revocationEndpoint: 'https://auth.example.com/oauth/revoke', clientCredentials: { clientId: 'resource-server', clientSecret: process.env.CLIENT_SECRET!, },
// Providers http: fetchHttpProvider({ timeoutMs: 5000 }), crypto: webCryptoProvider(), clock: systemClock(), jwksCache: memoryCache({ maxSize: 1000 }),});Provider System
Section titled “Provider System”The SDK uses a provider abstraction to decouple core logic from platform-specific implementations. Each provider has a default implementation that works on most runtimes.
HttpProvider
Section titled “HttpProvider”Handles all HTTP requests (JWKS fetching, introspection, revocation):
interface HttpProvider { fetch(url: string, init?: RequestInit): Promise<Response>;}Default: fetchHttpProvider() — uses the global fetch API.
Custom HTTP Provider
Section titled “Custom HTTP Provider”Add custom headers, logging, or proxy support:
import { fetchHttpProvider } from '@authrim/server/providers';
// With timeoutconst http = fetchHttpProvider({ timeoutMs: 5000 });
// Fully customconst customHttp: HttpProvider = { async fetch(url, init) { console.log(`HTTP ${init?.method ?? 'GET'} ${url}`);
const response = await fetch(url, { ...init, headers: { ...init?.headers, 'X-Custom-Header': 'value', }, });
console.log(`Response: ${response.status}`); return response; },};
const server = createAuthrimServer({ issuer: 'https://auth.example.com', audience: 'https://api.example.com', http: customHttp,});CryptoProvider
Section titled “CryptoProvider”Handles JWT signature verification and cryptographic operations:
interface CryptoProvider { verifySignature( algorithm: string, key: CryptoKey, signature: Uint8Array, data: Uint8Array, ): Promise<boolean>;
importJwk( jwk: JsonWebKey, algorithm: string, ): Promise<CryptoKey>;
sha256(data: Uint8Array): Promise<Uint8Array>;
calculateThumbprint(jwk: JsonWebKey): Promise<string>;}Default: webCryptoProvider() — uses the Web Crypto API (crypto.subtle).
ClockProvider
Section titled “ClockProvider”Provides the current time for token expiration and validity checks:
interface ClockProvider { nowMs(): number; nowSeconds(): number;}Default: systemClock() — uses Date.now().
Test Clock Example
Section titled “Test Clock Example”Use a controllable clock for unit tests:
function testClock(initialMs: number = Date.now()): ClockProvider & { advance(ms: number): void; set(ms: number): void;} { let currentMs = initialMs;
return { nowMs: () => currentMs, nowSeconds: () => Math.floor(currentMs / 1000), advance(ms: number) { currentMs += ms; }, set(ms: number) { currentMs = ms; }, };}
// In testsconst clock = testClock();const server = createAuthrimServer({ issuer: 'https://auth.example.com', audience: 'https://api.example.com', clock,});
// Simulate time passingclock.advance(3600 * 1000); // Advance 1 hourCacheProvider
Section titled “CacheProvider”Stores JWKS documents and other cached data:
interface CacheProvider<T = unknown> { get(key: string): Promise<T | undefined>; set(key: string, value: T, ttlMs: number): Promise<void>; delete(key: string): Promise<void>;}Default: memoryCache() — in-process memory cache.
Redis Cache Example
Section titled “Redis Cache Example”For multi-instance deployments, use a shared cache like Redis:
import { createClient } from 'redis';import type { CacheProvider } from '@authrim/server/providers';
function redisCache(redisClient: ReturnType<typeof createClient>): CacheProvider { return { async get(key) { const value = await redisClient.get(`authrim:${key}`); return value ? JSON.parse(value) : undefined; }, async set(key, value, ttlMs) { await redisClient.set( `authrim:${key}`, JSON.stringify(value), { PX: ttlMs }, ); }, async delete(key) { await redisClient.del(`authrim:${key}`); }, };}
// Usageconst redis = createClient({ url: process.env.REDIS_URL });await redis.connect();
const server = createAuthrimServer({ issuer: 'https://auth.example.com', audience: 'https://api.example.com', jwksCache: redisCache(redis),});Runtime-Specific Notes
Section titled “Runtime-Specific Notes”Node.js 18+
Section titled “Node.js 18+”All features are fully supported. The default providers use fetch (available since Node 18) and crypto.subtle (Web Crypto API).
// No special configuration neededconst server = createAuthrimServer({ issuer: 'https://auth.example.com', audience: 'https://api.example.com',});All features are fully supported. Bun implements the Web Crypto API and fetch natively.
// No special configuration neededconst server = createAuthrimServer({ issuer: 'https://auth.example.com', audience: 'https://api.example.com',});All features are supported. You may need import maps for the package:
{ "imports": { "@authrim/server": "npm:@authrim/server" }}import { createAuthrimServer } from '@authrim/server';
const server = createAuthrimServer({ issuer: 'https://auth.example.com', audience: 'https://api.example.com',});Cloudflare Workers
Section titled “Cloudflare Workers”Cloudflare Workers support the Web Crypto API and fetch. Use with the Hono adapter for the best experience.
import { Hono } from 'hono';import { createAuthrimServer } from '@authrim/server';import { authrimMiddleware, getAuth } from '@authrim/server/adapters/hono';
type Bindings = { AUTHRIM_ISSUER: string; AUTHRIM_AUDIENCE: string;};
const app = new Hono<{ Bindings: Bindings }>();
app.use('/api/*', async (c, next) => { const server = createAuthrimServer({ issuer: c.env.AUTHRIM_ISSUER, audience: c.env.AUTHRIM_AUDIENCE, }); return authrimMiddleware(server)(c, next);});
export default app;Vercel Edge Functions
Section titled “Vercel Edge Functions”Similar constraints to Cloudflare Workers. The Web Crypto API and fetch are available, but memory cache is per-invocation.
import { createAuthrimServer } from '@authrim/server';
const server = createAuthrimServer({ issuer: process.env.AUTHRIM_ISSUER!, audience: process.env.AUTHRIM_AUDIENCE!, jwksRefreshIntervalMs: 300000, // 5 minutes — shorter TTL for edge});createAuthrimServer() vs new AuthrimServer()
Section titled “createAuthrimServer() vs new AuthrimServer()”The SDK provides two ways to create a server instance:
createAuthrimServer() (Recommended)
Section titled “createAuthrimServer() (Recommended)”Recommended public factory for creating a configured server client:
import { createAuthrimServer } from '@authrim/server';
const server = createAuthrimServer({ issuer: 'https://auth.example.com', audience: 'https://api.example.com',});- Keeps application code aligned with the public SDK examples
- Returns a configured
AuthrimServerinstance - Uses the same configuration resolution as the constructor
- Throws
configuration_errorfor invalid config
new AuthrimServer()
Section titled “new AuthrimServer()”Direct constructor for advanced or low-level use cases:
import { AuthrimServer } from '@authrim/server';
const server = new AuthrimServer({ issuer: 'https://auth.example.com', audience: 'https://api.example.com',});Next Steps
Section titled “Next Steps”- Error Handling — Error codes and response utilities
- Express & Fastify Adapters — Framework integration
- Hono, Koa & NestJS Adapters — Additional framework adapters
- Back-Channel Logout — Server-side logout handling