コンテンツにスキップ

インストールとクイックスタート

インストール

Terminal window
npm install @authrim/server

その他のパッケージマネージャを使用する場合:

Terminal window
pnpm add @authrim/server
yarn add @authrim/server

前提条件

@authrim/serverを使用する前に、以下が必要です。

  1. Authrimインスタンス — 稼働中のAuthrim認可サーバー(またはOAuth 2.0/OIDC準拠の任意の発行者)
  2. 登録済みのOAuthクライアント — トークンを取得してAPIを呼び出すクライアントアプリケーション
  3. オーディエンス値 — リソースサーバーを識別する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 startup
await authrim.init();

設定オプション

オプションデフォルト説明
issuerstring | string[]信頼する発行者URL。必須。
audiencestring | string[]期待するオーディエンス値。必須。
jwksUristring自動検出JWKSエンドポイントURL。自動検出を上書きします。
clockToleranceSecondsnumber60exp/nbf/iatクレームのクロックスキュー許容値。
jwksRefreshIntervalMsnumber3600000 (1時間)JWKSリフレッシュの最小間隔。
introspectionEndpointstringトークンイントロスペクションエンドポイントURL。
revocationEndpointstringトークン失効エンドポイントURL。
clientCredentialsobjectイントロスペクション/失効用の{ clientId, clientSecret }
requireHttpsbooleantrueすべての外部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 AuthrimServer
const authrim = new AuthrimServer({
issuer: 'https://auth.example.com',
audience: 'https://api.example.com',
});
await authrim.init();
// 2. Public endpoint — no authentication required
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
// 3. Protected endpoint — requires valid access token
app.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 scopes
app.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を取得してキャッシュします。

次のステップ