Configuration Reference
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
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
| Field | Type | Default | Description |
|---|---|---|---|
algorithms | string[] | ['RS256'] | Accepted JWT signing algorithms |
jwksUri | string | {issuer}/.well-known/jwks.json | JWKS endpoint URL. Auto-derived from issuer if not set |
jwksCacheTtlMs | number | 600000 (10 min) | JWKS cache TTL in milliseconds |
clockToleranceSeconds | number | 60 | Clock skew tolerance for exp/nbf/iat checks |
requiredClaims | string[] | [] | Claims that must be present in the token |
dpop | DPoPConfig | false | false | DPoP validation configuration |
introspection | IntrospectionConfig | undefined | Token introspection endpoint configuration |
revocation | RevocationConfig | undefined | Token revocation endpoint configuration |
http | HttpProvider | fetchHttpProvider() | HTTP provider for network requests |
crypto | CryptoProvider | webCryptoProvider() | Cryptographic operations provider |
clock | ClockProvider | systemClock() | Clock provider for time-based checks |
cache | CacheProvider | memoryCache() | Cache provider for JWKS and related data |
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: RS256 algorithm, auto-discovered JWKS URI, in-memory cache, and the Web Crypto API.
Full Configuration Example
import { createAuthrimServer } from '@authrim/server';import { fetchHttpProvider, webCryptoProvider, systemClock, memoryCache,} from '@authrim/server';
const server = createAuthrimServer({ // Required issuer: 'https://auth.example.com', audience: 'https://api.example.com',
// JWT validation algorithms: ['RS256', 'ES256'], clockToleranceSeconds: 30, requiredClaims: ['sub', 'email'],
// JWKS jwksUri: 'https://auth.example.com/.well-known/jwks.json', jwksCacheTtlMs: 600000, // 10 minutes
// DPoP dpop: { required: false, allowedAlgorithms: ['ES256'], maxIatAgeSeconds: 300, },
// Token introspection introspection: { endpoint: 'https://auth.example.com/oauth/introspect', clientId: 'resource-server', clientSecret: process.env.CLIENT_SECRET, },
// Token revocation revocation: { endpoint: 'https://auth.example.com/oauth/revoke', clientId: 'resource-server', clientSecret: process.env.CLIENT_SECRET, },
// Providers http: fetchHttpProvider({ timeoutMs: 5000 }), crypto: webCryptoProvider(), clock: systemClock(), cache: memoryCache({ maxSize: 1000 }),});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
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
Add custom headers, logging, or proxy support:
import { fetchHttpProvider } from '@authrim/server';
// 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
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
Provides the current time for token expiration and validity checks:
interface ClockProvider { nowMs(): number; nowSeconds(): number;}Default: systemClock() — uses Date.now().
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
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
For multi-instance deployments, use a shared cache like Redis:
import { createClient } from 'redis';import type { CacheProvider } from '@authrim/server';
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', cache: redisCache(redis),});Runtime-Specific Notes
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',});Bun
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',});Deno
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
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
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!, jwksCacheTtlMs: 300000, // 5 minutes — shorter TTL for edge});createAuthrimServer() vs new AuthrimServer()
The SDK provides two ways to create a server instance:
createAuthrimServer() (Recommended)
Factory function that applies defaults and validates configuration:
import { createAuthrimServer } from '@authrim/server';
const server = createAuthrimServer({ issuer: 'https://auth.example.com', audience: 'https://api.example.com',});- Validates required fields at creation time
- Applies default providers automatically
- Returns a fully configured
AuthrimServerinstance - Throws
configuration_errorfor invalid config
new AuthrimServer()
Direct constructor for advanced use cases:
import { AuthrimServer } from '@authrim/server';
const server = new AuthrimServer({ issuer: 'https://auth.example.com', audience: 'https://api.example.com', // Must provide all required fields — no defaults applied});Next Steps
- Error Handling — Error codes and response utilities
- Express & Fastify Adapters — Framework integration
- Hono, Koa & NestJS Adapters — Additional framework adapters
- SCIM 2.0 Client — User and group provisioning
- Back-Channel Logout — Server-side logout handling