Skip to content

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

FieldTypeDescription
issuerstring | string[]Expected token issuer (iss claim). Must match the Authorization Server’s issuer URL
audiencestring | string[]Expected token audience (aud claim). Your Resource Server identifier

Optional Fields

FieldTypeDefaultDescription
algorithmsstring[]['RS256']Accepted JWT signing algorithms
jwksUristring{issuer}/.well-known/jwks.jsonJWKS endpoint URL. Auto-derived from issuer if not set
jwksCacheTtlMsnumber600000 (10 min)JWKS cache TTL in milliseconds
clockToleranceSecondsnumber60Clock skew tolerance for exp/nbf/iat checks
requiredClaimsstring[][]Claims that must be present in the token
dpopDPoPConfig | falsefalseDPoP validation configuration
introspectionIntrospectionConfigundefinedToken introspection endpoint configuration
revocationRevocationConfigundefinedToken revocation endpoint configuration
httpHttpProviderfetchHttpProvider()HTTP provider for network requests
cryptoCryptoProviderwebCryptoProvider()Cryptographic operations provider
clockClockProvidersystemClock()Clock provider for time-based checks
cacheCacheProvidermemoryCache()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 timeout
const http = fetchHttpProvider({ timeoutMs: 5000 });
// Fully custom
const 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 tests
const clock = testClock();
const server = createAuthrimServer({
issuer: 'https://auth.example.com',
audience: 'https://api.example.com',
clock,
});
// Simulate time passing
clock.advance(3600 * 1000); // Advance 1 hour

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

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}`);
},
};
}
// Usage
const 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 needed
const 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 needed
const 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:

deno.json
{
"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:

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 AuthrimServer instance
  • Throws configuration_error for 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