コンテンツにスキップ

設定リファレンス

AuthrimServerConfig オブジェクトは、トークン検証、JWKSフェッチ、DPoPサポート、プロバイダー実装を設定します。このページでは、すべての設定フィールド、プロバイダーシステム、ランタイム固有の注意点について説明します。

フィールド説明
issuerstring | string[]期待されるトークンのissuer(issクレーム)。認可サーバーのissuer URLと一致する必要があります
audiencestring | string[]期待されるトークンのaudience(audクレーム)。リソースサーバーの識別子
フィールドデフォルト説明
jwksUristringOIDC discoveryJWKSエンドポイントURL。複数issuerを設定した場合、この共有URIはすべてのissuerで使われます
jwksUriByIssuerRecord<string, string>{}issuer別のJWKSエンドポイント。設定済みissuerだけが受け入れられます
dynamicJwksDiscoverybooleantrue明示的なURIがない場合、許可された各issuerのOpenID ConfigurationからJWKSを発見します
jwksRefreshIntervalMsnumber3600000(1時間)JWKSキャッシュTTL / リフレッシュ間隔(ミリ秒)
clockToleranceSecondsnumber60exp/nbf/iatチェックのクロックスキュー許容値
introspectionEndpointstringundefined共有トークンイントロスペクションエンドポイント
introspectionEndpointByIssuerRecord<string, string>{}issuer別イントロスペクションエンドポイント
revocationEndpointstringundefined共有トークン失効エンドポイント
revocationEndpointByIssuerRecord<string, string>{}issuer別トークン失効エンドポイント
stepUpEndpointstring{issuer}/auth/step-up共有canonical Step-Upエンドポイントベース
stepUpEndpointByIssuerRecord<string, string>{}issuer別Step-Upエンドポイントベース
clientCredentials{ clientId: string; clientSecret: string }undefinedイントロスペクションと失効で使うクライアント認証情報
tokenValidationOmit<TokenValidationOptions, 'issuer' | 'audience'>{}scopeやtenant policyなどの追加検証ルール
httpHttpProviderfetchHttpProvider()ネットワークリクエスト用のHTTPプロバイダー
cryptoCryptoProviderwebCryptoProvider()暗号化操作プロバイダー
clockClockProvidersystemClock()時刻ベースのチェック用クロックプロバイダー
jwksCacheCacheProvider<CachedJwk[]>memoryCache()JWKSデータ用キャッシュプロバイダー
requireHttpsbooleantrueissuerとセキュリティ上重要なエンドポイントURLにHTTPSを要求

最もシンプルなセットアップでは issueraudience のみが必要です:

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。

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 }),
});

SDKはプロバイダー抽象化を使用して、コアロジックをプラットフォーム固有の実装から分離します。各プロバイダーには、ほとんどのランタイムで動作するデフォルト実装があります。

すべてのHTTPリクエスト(JWKSフェッチ、イントロスペクション、失効)を処理します:

interface HttpProvider {
fetch(url: string, init?: RequestInit): Promise<Response>;
}

デフォルト: fetchHttpProvider() — グローバルの fetch APIを使用。

カスタムヘッダー、ロギング、プロキシサポートを追加します:

import { fetchHttpProvider } from '@authrim/server/providers';
// 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,
});

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)を使用。

トークンの有効期限と有効性チェックのための現在時刻を提供します:

interface ClockProvider {
nowMs(): number;
nowSeconds(): number;
}

デフォルト: systemClock()Date.now() を使用。

ユニットテスト用に制御可能なクロックを使用します:

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

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などの共有キャッシュを使用します:

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}`);
},
};
}
// 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',
jwksCache: redisCache(redis),
});

すべての機能が完全にサポートされています。デフォルトプロバイダーは fetch(Node 18以降で利用可能)と crypto.subtle(Web Crypto API)を使用します。

// No special configuration needed
const server = createAuthrimServer({
issuer: 'https://auth.example.com',
audience: 'https://api.example.com',
});

すべての機能が完全にサポートされています。BunはWeb Crypto APIと fetch をネイティブに実装しています。

// No special configuration needed
const server = createAuthrimServer({
issuer: 'https://auth.example.com',
audience: 'https://api.example.com',
});

すべての機能がサポートされています。パッケージにはインポートマップが必要な場合があります:

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は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;

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つの方法を提供します:

設定済みのサーバークライアントを作成する、推奨の公開ファクトリです:

import { createAuthrimServer } from '@authrim/server';
const server = createAuthrimServer({
issuer: 'https://auth.example.com',
audience: 'https://api.example.com',
});
  • アプリケーションコードを公開SDK例と揃えられる
  • 設定済みの AuthrimServer インスタンスを返す
  • コンストラクタと同じ設定解決パスを使用する
  • 無効な設定に対して configuration_error をスロー

高度または低レベルのユースケース向けの直接コンストラクタです:

import { AuthrimServer } from '@authrim/server';
const server = new AuthrimServer({
issuer: 'https://auth.example.com',
audience: 'https://api.example.com',
});