概要
@authrim/serverとは?
Section titled “@authrim/serverとは?”@authrim/serverは、リソースサーバー向けのAuthrimサーバーサイドSDKです。JWTアクセストークンの検証、DPoPプルーフの検証、issuer単位のJWKS鍵セット管理、Node.jsフレームワーク向けミドルウェアを提供します。イントロスペクション、失効、Native SSO device secret、canonical Step-Up、Customer Profile protected resource、Cookie Session CSRF、バックチャネルログアウト向けのサーバーサイドヘルパーも含まれます。
アーキテクチャ
Section titled “アーキテクチャ”以下の図は、OAuth 2.0アーキテクチャにおける@authrim/serverの位置づけを示しています。
sequenceDiagram
participant Client as クライアントアプリ<br>(@authrim/web or<br>@authrim/core)
participant AuthServer as Authrim<br>認可サーバー
participant Resource as リソースサーバー<br>(@authrim/server)
Client->>AuthServer: 1. 認可リクエスト
AuthServer-->>Client: 2. アクセストークン (JWT)
Client->>Resource: 3. APIリクエスト + アクセストークン
Resource->>AuthServer: 4. JWKS取得 (キャッシュ)
Resource->>Resource: 5. トークン検証
Resource-->>Client: 6. 保護されたリソース
SDKはステップ4と5を自動的に処理し、認可サーバーの公開鍵を取得・キャッシュした上で、トークンの署名とクレームを検証します。
パッケージエントリポイント
Section titled “パッケージエントリポイント”| エクスポートパス | 目的 | 主要エクスポート |
|---|---|---|
@authrim/server | メインエントリ — クライアントファクトリ、型、バリデータ、JWKS、Step-Up、Customer Profile、セッションユーティリティ | createAuthrimServer, AuthrimServer, StepUpClient, CustomerProfileClient, BackChannelLogoutValidator |
@authrim/server/providers | プロバイダーインターフェースとユーティリティ | CryptoProvider, HttpProvider, ClockProvider, CacheProvider |
@authrim/server/adapters/express | Expressミドルウェア | authrimMiddleware, authrimOptionalMiddleware |
@authrim/server/adapters/fastify | Fastifyフックとプラグイン | authrimPreHandler, authrimPlugin, authrimOptionalPreHandler, authrimOptionalPlugin |
@authrim/server/adapters/hono | Honoミドルウェア | authrimMiddleware, authrimOptionalMiddleware, getAuth, getAuthTokenType |
@authrim/server/adapters/koa | Koaミドルウェア | authrimMiddleware, authrimOptionalMiddleware |
@authrim/server/adapters/nestjs | NestJSガードとユーティリティ | createAuthrimGuard, createAuthrimOptionalGuard, getAuthFromRequest, getAuthTokenTypeFromRequest |
- JWTアクセストークン検証 — 署名検証、クレーム検証(iss、aud、exp、nbf、iat)、スコープの適用
- DPoPプルーフ検証(RFC 9449) — JWK Thumbprintバインディングによる送信者制約トークンの検証
- JWKS管理 — 自動ディスカバリ、Cache-Controlによるキャッシュ、鍵ローテーション対応、シングルフライトフェッチ
- マルチissuerリソースサーバー — 複数issuerの許可リストと、issuer別JWKS・イントロスペクション・失効・Step-Upエンドポイント設定
- トークンイントロスペクション(RFC 7662) — 認可サーバーへの不透明トークンの状態問い合わせ
- トークン失効(RFC 7009) — 認可サーバーでのトークン失効
- Native SSO device secret操作 — 生の
device_secretをログに出さずにイントロスペクト・失効 - Canonical Step-Up — サーバーコードからStep-Upアクションの開始、取得、完了、再送、キャンセルを実行
- Customer Profile protected resource API — elevation grantによる読み取りとdelegated write
- Cookie Sessionセキュリティ — Direct Auth artifact redeem、double-submit CSRF、Cookie属性解決のヘルパー
- バックチャネルログアウト(OIDC 1.0) — 認可サーバーからのログアウトトークンの検証
- フレームワークミドルウェア — Express、Fastify、Hono、Koa、NestJS向けのすぐに使えるアダプタ
- セキュリティ強化 — タイミングセーフ比較、
alg:none拒否、SSRF対策、JWTサイズ制限
サポートされるアルゴリズム
Section titled “サポートされるアルゴリズム”| ファミリー | アルゴリズム |
|---|---|
| RSA PKCS#1 v1.5 | RS256, RS384, RS512 |
| RSA-PSS | PS256, PS384, PS512 |
| ECDSA | ES256, ES384, ES512 |
| EdDSA | EdDSA |
サポートされるランタイム
Section titled “サポートされるランタイム”@authrim/serverは、標準的なWeb Crypto APIをサポートするあらゆるJavaScriptランタイムで動作します。
- Node.js 18+
- Bun
- Deno
- Cloudflare Workers
- Vercel Edge Runtime
@authrim/serverは、3つのフェーズでアクセストークンを検証します。
- 初期化 — 起動時に、SDKは認可サーバーのOIDCディスカバリドキュメントとJWKS(公開鍵)を取得します。これらはメモリにキャッシュされます。
- トークン検証 — 各リクエストに対して、SDKはJWTを解析し、
kidによって正しい署名鍵を選択し、暗号署名を検証し、すべての標準クレーム(発行者、オーディエンス、有効期限など)を検証します。 - 継続的な鍵管理 — SDKは鍵の鮮度を監視し、Cache-Controlヘッダーを処理し、新しい
kidが検出された際に自動的に鍵を再取得します(鍵ローテーション)。
これらはすべて、起動時のinit()とリクエストごとのvalidateToken()という2つのメソッド呼び出しにカプセル化されています。
AuthrimServerメソッド
Section titled “AuthrimServerメソッド”| メソッド | 説明 |
|---|---|
init() | OIDCディスカバリドキュメントとJWKSを取得します。起動時に一度呼び出してください。 |
validateToken(token) | 設定済みの検証ルールでJWTアクセストークンを検証します。 |
validateDPoP(proof, options) | DPoPプルーフJWTを検証します(RFC 9449)。 |
introspect(token, tokenTypeHint?, issuerOptions?) | 認可サーバーにトークンの状態を問い合わせます(RFC 7662)。 |
revoke(token, tokenTypeHint?, issuerOptions?) | 認可サーバーでトークンを失効させます(RFC 7009)。 |
introspectDeviceSecret(deviceSecret, issuerOptions?) | Native SSO device_secret の状態を問い合わせます。 |
revokeDeviceSecret(deviceSecret, issuerOptions?) | Native SSO device_secret を失効させます。 |
stepUp.start() / startStepUp() | step_up_token からcanonical Step-Upアクションを開始します。 |
customerProfiles.getWithElevationGrant() | elevation grantを使ってCustomer Profileを読み取ります。 |
customerProfiles.updateDelegated() | Customer Profileのdelegated writeを実行します。 |
invalidateJwksCache() | 次の検証時にJWKSを強制的に再取得します。 |
import { createAuthrimServer } from '@authrim/server';
const authrim = createAuthrimServer({ issuer: 'https://auth.example.com', audience: 'https://api.example.com', tokenValidation: { requiredScopes: ['profile:read'], requireTenantClaim: true, },});
// Initialize once at startup (fetches JWKS)await authrim.init();
// Validate an incoming access tokenconst result = await authrim.validateToken(bearerToken);if (result.error) { throw new Error(result.error.message);}
console.log(result.data.claims.sub); // Subject (user ID)console.log(result.data.claims.scope); // Granted scopesconsole.log(result.data.issuer); // Validated issuerconsole.log(result.data.tenantId); // Tenant claim when presentconsole.log(result.data.tokenType); // 'Bearer' or 'DPoP'console.log(result.data.expiresIn); // Seconds until expirationフレームワークミドルウェアを使用する場合
Section titled “フレームワークミドルウェアを使用する場合”validateToken()を手動で呼び出す代わりに、フレームワークアダプタを使用してトークンの抽出と検証を自動化できます。
import express from 'express';import { createAuthrimServer } from '@authrim/server';import { authrimMiddleware } from '@authrim/server/adapters/express';
const app = express();const authrim = createAuthrimServer({ issuer: 'https://auth.example.com', audience: 'https://api.example.com',});await authrim.init();
// Protected route — token validated automaticallyapp.get('/api/me', authrimMiddleware(authrim), (req, res) => { res.json({ userId: req.auth.claims.sub });});
// Protected route with required scopesapp.delete('/api/users/:id', authrimMiddleware(authrim, { requiredScopes: ['admin:write'] }), (req, res) => { res.json({ deleted: true });});
app.listen(3000);@authrim/serverを使用すべき場面
Section titled “@authrim/serverを使用すべき場面”| シナリオ | パッケージ | 説明 |
|---|---|---|
| APIでトークンを検証する | @authrim/server | このSDK — リソースサーバー向け |
| ブラウザ経由でユーザーをログインさせる | @authrim/web | ブラウザベースのOAuth/OIDCフロー |
| SvelteKitフルスタック認証 | @authrim/sveltekit | サーバーフック + Svelteストア |
| カスタムOAuthクライアントを構築する | @authrim/core | プラットフォーム非依存のプロトコルライブラリ |
| 仕様 | RFC | カバー範囲 |
|---|---|---|
| JSON Web Token (JWT) | RFC 7519 | トークン解析とクレーム検証 |
| JSON Web Key (JWK) | RFC 7517 | JWKSフェッチ、鍵インポート、鍵選択 |
| JWK Thumbprint | RFC 7638 | DPoP Thumbprint計算とバインディング |
| Token Introspection | RFC 7662 | 完全なイントロスペクションクライアント |
| Token Revocation | RFC 7009 | 完全な失効クライアント |
| DPoP | RFC 9449 | ステートレスなプルーフ検証、Thumbprintバインディング |
| OIDC Core 1.0 | — | IDトークンとクレーム検証 |
| OIDC Back-Channel Logout 1.0 | — | ログアウトトークン検証 |
次のステップ
Section titled “次のステップ”- インストールとクイックスタート — SDKをインストールして最初の保護されたAPIをセットアップする
- セキュリティに関する考慮事項 — 本番デプロイのための必須セキュリティガイダンス
- トークン検証 — 詳細なトークン検証APIとパイプライン
- DPoP検証 — 送信者制約トークンの検証
- JWKS管理 — 鍵のディスカバリ、キャッシュ、ローテーション
- イントロスペクションと失効 — 認可サーバーでのトークンの問い合わせと失効