インストールとクイックスタート
インストール
npm install @authrim/serverその他のパッケージマネージャを使用する場合:
pnpm add @authrim/serveryarn add @authrim/server前提条件
@authrim/serverを使用する前に、以下が必要です。
- Authrimインスタンス — 稼働中のAuthrim認可サーバー(またはOAuth 2.0/OIDC準拠の任意の発行者)
- 登録済みのOAuthクライアント — トークンを取得してAPIを呼び出すクライアントアプリケーション
- オーディエンス値 — リソースサーバーを識別するURI(例:
https://api.example.com)
AuthrimServerの初期化
AuthrimServerインスタンスを作成して初期化します。
import { AuthrimServer } from '@authrim/server';
const authrim = new AuthrimServer({ // Required: your authorization server's issuer URL issuer: 'https://auth.example.com',
// Required: your resource server's audience identifier audience: 'https://api.example.com',});
// Call init() once at application startupawait authrim.init();設定オプション
| オプション | 型 | デフォルト | 説明 |
|---|---|---|---|
issuer | string | string[] | — | 信頼する発行者URL。必須。 |
audience | string | string[] | — | 期待するオーディエンス値。必須。 |
jwksUri | string | 自動検出 | JWKSエンドポイントURL。自動検出を上書きします。 |
clockToleranceSeconds | number | 60 | exp/nbf/iatクレームのクロックスキュー許容値。 |
jwksRefreshIntervalMs | number | 3600000 (1時間) | JWKSリフレッシュの最小間隔。 |
introspectionEndpoint | string | — | トークンイントロスペクションエンドポイントURL。 |
revocationEndpoint | string | — | トークン失効エンドポイントURL。 |
clientCredentials | object | — | イントロスペクション/失効用の{ clientId, clientSecret }。 |
requireHttps | boolean | true | すべての外部URLにHTTPSを強制します。 |
エンドツーエンドクイックスタート: Express API
アクセストークンを検証してエンドポイントを保護する、完全なExpress APIサーバーの例を示します。
import express from 'express';import { AuthrimServer } from '@authrim/server';import { authrimMiddleware } from '@authrim/server/adapters/express';
const app = express();
// 1. Create and initialize AuthrimServerconst authrim = new AuthrimServer({ issuer: 'https://auth.example.com', audience: 'https://api.example.com',});
await authrim.init();
// 2. Public endpoint — no authentication requiredapp.get('/health', (req, res) => { res.json({ status: 'ok' });});
// 3. Protected endpoint — requires valid access tokenapp.get('/api/profile', authrimMiddleware(authrim), (req, res) => { const token = req.auth; res.json({ userId: token.claims.sub, scope: token.claims.scope, tokenType: token.tokenType, });});
// 4. Protected endpoint with required scopesapp.get('/api/admin/users', authrimMiddleware(authrim, { requiredScopes: ['admin:read'] }), (req, res) => { res.json({ users: [] });});
app.listen(3000, () => { console.log('API server running on http://localhost:3000');});このサーバーは以下を行います:
- 起動時に認可サーバーの公開鍵を取得してキャッシュ
- 保護されたルートでJWTアクセストークンを検証
- 指定された場合、必要なスコープをチェック
req.auth経由で検証済みトークンを利用可能に
クイックスタート: Hono + Cloudflare Workers
@authrim/serverはエッジランタイムでも動作します。以下はCloudflare Workers向けのHonoアプリケーションの例です。
import { Hono } from 'hono';import { AuthrimServer } from '@authrim/server';import { authrimMiddleware, getAuth } from '@authrim/server/adapters/hono';
type Env = { ISSUER: string; AUDIENCE: string;};
const app = new Hono<{ Bindings: Env }>();
// Initialize AuthrimServer per request (Workers are stateless)app.use('/api/*', async (c, next) => { const authrim = new AuthrimServer({ issuer: c.env.ISSUER, audience: c.env.AUDIENCE, }); await authrim.init();
const middleware = authrimMiddleware(authrim); return middleware(c, next);});
app.get('/api/profile', (c) => { const token = getAuth(c); return c.json({ userId: token.claims.sub, scope: token.claims.scope, });});
export default app;HTTPSの要件
デフォルトでは、@authrim/serverはすべての外部URL(発行者、JWKSエンドポイント、イントロスペクション、失効)にHTTPSを強制します。これにより、暗号化されていない接続でのトークン漏洩を防止します。
ローカル開発では、このチェックを無効にできます。
const authrim = new AuthrimServer({ issuer: 'http://localhost:4000', audience: 'http://localhost:3000', requireHttps: false, // Only for local development!});複数の発行者
リソースサーバーが複数の認可サーバーからのトークンを受け入れる場合は、配列で指定します。
const authrim = new AuthrimServer({ issuer: [ 'https://auth.example.com', 'https://auth.partner.com', ], audience: 'https://api.example.com',});SDKはinit()時にすべての発行者からJWKSを取得してキャッシュします。
次のステップ
- セキュリティに関する考慮事項 — 本番環境に移行する前の必須セキュリティガイダンス
- トークン検証 — 詳細な検証APIとクレーム処理
- DPoP検証 — 送信者制約トークンの検証
- JWKS管理 — 鍵のキャッシュ、ローテーション、カスタムキャッシュプロバイダー
- イントロスペクションと失効 — トークンの問い合わせと失効