設定リファレンス
AuthrimServerConfig オブジェクトは、トークン検証、JWKSフェッチ、DPoPサポート、プロバイダー実装を設定します。このページでは、すべての設定フィールド、プロバイダーシステム、ランタイム固有の注意点について説明します。
AuthrimServerConfigリファレンス
Section titled “AuthrimServerConfigリファレンス”必須フィールド
Section titled “必須フィールド”| フィールド | 型 | 説明 |
|---|---|---|
issuer | string | string[] | 期待されるトークンのissuer(issクレーム)。認可サーバーのissuer URLと一致する必要があります |
audience | string | string[] | 期待されるトークンのaudience(audクレーム)。リソースサーバーの識別子 |
オプションフィールド
Section titled “オプションフィールド”| フィールド | 型 | デフォルト | 説明 |
|---|---|---|---|
jwksUri | string | OIDC discovery | JWKSエンドポイントURL。複数issuerを設定した場合、この共有URIはすべてのissuerで使われます |
jwksUriByIssuer | Record<string, string> | {} | issuer別のJWKSエンドポイント。設定済みissuerだけが受け入れられます |
dynamicJwksDiscovery | boolean | true | 明示的なURIがない場合、許可された各issuerのOpenID ConfigurationからJWKSを発見します |
jwksRefreshIntervalMs | number | 3600000(1時間) | JWKSキャッシュTTL / リフレッシュ間隔(ミリ秒) |
clockToleranceSeconds | number | 60 | exp/nbf/iatチェックのクロックスキュー許容値 |
introspectionEndpoint | string | undefined | 共有トークンイントロスペクションエンドポイント |
introspectionEndpointByIssuer | Record<string, string> | {} | issuer別イントロスペクションエンドポイント |
revocationEndpoint | string | undefined | 共有トークン失効エンドポイント |
revocationEndpointByIssuer | Record<string, string> | {} | issuer別トークン失効エンドポイント |
stepUpEndpoint | string | {issuer}/auth/step-up | 共有canonical Step-Upエンドポイントベース |
stepUpEndpointByIssuer | Record<string, string> | {} | issuer別Step-Upエンドポイントベース |
clientCredentials | { clientId: string; clientSecret: string } | undefined | イントロスペクションと失効で使うクライアント認証情報 |
tokenValidation | Omit<TokenValidationOptions, 'issuer' | 'audience'> | {} | scopeやtenant policyなどの追加検証ルール |
http | HttpProvider | fetchHttpProvider() | ネットワークリクエスト用のHTTPプロバイダー |
crypto | CryptoProvider | webCryptoProvider() | 暗号化操作プロバイダー |
clock | ClockProvider | systemClock() | 時刻ベースのチェック用クロックプロバイダー |
jwksCache | CacheProvider<CachedJwk[]> | memoryCache() | JWKSデータ用キャッシュプロバイダー |
requireHttps | boolean | true | issuerとセキュリティ上重要なエンドポイントURLにHTTPSを要求 |
最もシンプルなセットアップでは issuer と audience のみが必要です:
import { createAuthrimServer } from '@authrim/server';
const server = createAuthrimServer({ issuer: 'https://auth.example.com', audience: 'https://api.example.com',});これはすべてのデフォルト値を使用します:issuerのOpenID Configurationからの動的JWKS discovery、1時間のインメモリJWKSキャッシュ、60秒のクロック許容値、HTTPS強制、Web Crypto API。
完全な設定例
Section titled “完全な設定例”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 }),});プロバイダーシステム
Section titled “プロバイダーシステム”SDKはプロバイダー抽象化を使用して、コアロジックをプラットフォーム固有の実装から分離します。各プロバイダーには、ほとんどのランタイムで動作するデフォルト実装があります。
HttpProvider
Section titled “HttpProvider”すべてのHTTPリクエスト(JWKSフェッチ、イントロスペクション、失効)を処理します:
interface HttpProvider { fetch(url: string, init?: RequestInit): Promise<Response>;}デフォルト: fetchHttpProvider() — グローバルの fetch APIを使用。
カスタムHTTPプロバイダー
Section titled “カスタムHTTPプロバイダー”カスタムヘッダー、ロギング、プロキシサポートを追加します:
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”JWT署名の検証と暗号化操作を処理します:
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>;}デフォルト: webCryptoProvider() — Web Crypto API(crypto.subtle)を使用。
ClockProvider
Section titled “ClockProvider”トークンの有効期限と有効性チェックのための現在時刻を提供します:
interface ClockProvider { nowMs(): number; nowSeconds(): number;}デフォルト: systemClock() — Date.now() を使用。
テスト用クロックの例
Section titled “テスト用クロックの例”ユニットテスト用に制御可能なクロックを使用します:
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”JWKSドキュメントおよびその他のキャッシュデータを保存します:
interface CacheProvider<T = unknown> { get(key: string): Promise<T | undefined>; set(key: string, value: T, ttlMs: number): Promise<void>; delete(key: string): Promise<void>;}デフォルト: memoryCache() — プロセス内メモリキャッシュ。
Redisキャッシュの例
Section titled “Redisキャッシュの例”マルチインスタンスデプロイメントでは、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),});ランタイム固有の注意点
Section titled “ランタイム固有の注意点”Node.js 18以降
Section titled “Node.js 18以降”すべての機能が完全にサポートされています。デフォルトプロバイダーは fetch(Node 18以降で利用可能)と crypto.subtle(Web Crypto API)を使用します。
// No special configuration neededconst server = createAuthrimServer({ issuer: 'https://auth.example.com', audience: 'https://api.example.com',});すべての機能が完全にサポートされています。BunはWeb Crypto APIと fetch をネイティブに実装しています。
// No special configuration neededconst server = createAuthrimServer({ issuer: 'https://auth.example.com', audience: 'https://api.example.com',});すべての機能がサポートされています。パッケージにはインポートマップが必要な場合があります:
{ "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はWeb Crypto APIと fetch をサポートしています。最適な体験にはHonoアダプターを使用してください。
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”Cloudflare Workersと同様の制約があります。Web Crypto APIと fetch は利用可能ですが、メモリキャッシュは呼び出しごとに初期化されます。
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()”SDKはサーバーインスタンスを作成する2つの方法を提供します:
createAuthrimServer()(推奨)
Section titled “createAuthrimServer()(推奨)”設定済みのサーバークライアントを作成する、推奨の公開ファクトリです:
import { createAuthrimServer } from '@authrim/server';
const server = createAuthrimServer({ issuer: 'https://auth.example.com', audience: 'https://api.example.com',});- アプリケーションコードを公開SDK例と揃えられる
- 設定済みの
AuthrimServerインスタンスを返す - コンストラクタと同じ設定解決パスを使用する
- 無効な設定に対して
configuration_errorをスロー
new AuthrimServer()
Section titled “new AuthrimServer()”高度または低レベルのユースケース向けの直接コンストラクタです:
import { AuthrimServer } from '@authrim/server';
const server = new AuthrimServer({ issuer: 'https://auth.example.com', audience: 'https://api.example.com',});次のステップ
Section titled “次のステップ”- エラーハンドリング — エラーコードとレスポンスユーティリティ
- Express & Fastifyアダプター — フレームワーク統合
- Hono、Koa & NestJSアダプター — その他のフレームワークアダプター
- バックチャネルログアウト — サーバーサイドのログアウト処理