JWT(JSON形式のセキュリティ認証情報)ベアラートークンの検証やアクセス権限の確認を使ってFastify APIのエンドポイント(データ提供の窓口)を保護する必要があるとき。 フロントエンドやモバイルアプリから受け取ったアクセストークンを検証する、ステートレス(状態管理を必要としない)なAPI構築に @auth0/auth0-fastify-api と統合して使用します。
Use when protecting Fastify API endpoints with JWT Bearer token validation or scope checks. Integrates @auth0/auth0-fastify-api for stateless APIs receiving access tokens from frontends or mobile apps.
@auth0/auth0-fastify-api を使用して、JWT アクセストークンの検証により Fastify API エンドポイントを保護します。
auth0-quickstart スキルを使用してください@auth0/auth0-fastify を使用auth0-react、auth0-vue、または auth0-angular を使用auth0-nextjs スキルを使用auth0-react-native を使用npm install @auth0/auth0-fastify-api fastify dotenv
Auth0 に API(Application ではなく)を作成します:
# Auth0 CLI を使用する場合
auth0 apis create \
--name "My Fastify API" \
--identifier https://my-api.example.com
または Auth0 ダッシュボード → Applications → APIs から手動で作成することもできます。
.env を作成します:
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_AUDIENCE=https://my-api.example.com
Fastify サーバーを作成します(server.js):
import 'dotenv/config';
import Fastify from 'fastify';
import fastifyAuth0Api from '@auth0/auth0-fastify-api';
const fastify = Fastify({ logger: true });
// Auth0 API plugin を登録
await fastify.register(fastifyAuth0Api, {
domain: process.env.AUTH0_DOMAIN,
audience: process.env.AUTH0_AUDIENCE,
});
fastify.listen({ port: 3001 });
// パブリックルート — 認証不要
fastify.get('/api/public', async (request, reply) => {
return {
message: 'Hello from a public endpoint!',
timestamp: new Date().toISOString(),
};
});
// 保護されたルート — 有効な JWT が必要
fastify.get('/api/private', {
preHandler: fastify.requireAuth()
}, async (request, reply) => {
return {
message: 'Hello from a protected endpoint!',
user: request.user.sub,
timestamp: new Date().toISOString(),
};
});
// ユーザー情報付きの保護されたルート
fastify.get('/api/profile', {
preHandler: fastify.requireAuth()
}, async (request, reply) => {
return {
profile: request.user, // JWT クレーム
};
});
パブリックエンドポイントのテスト:
curl http://localhost:3001/api/public
保護されたエンドポイントのテスト(アクセストークンが必要):
# まずアクセストークンを取得する(例: Auth0 ダッシュボード > APIs > Test タブ)
curl http://localhost:3001/api/private \
-H "Authorization: Bearer $ACCESS_TOKEN"
| 間違い | 対処法 |
|---|---|
| Auth0 で API ではなく Application を作成した | Auth0 ダッシュボード → Applications → APIs で API リソースを作成すること |
| Authorization ヘッダーが不足している | 保護されたエンドポイントへのすべてのリクエストに Authorization: Bearer <token> を含めること |
| トークンの audience が一致していない | クライアントは一致する audience パラメータを指定してトークンをリクエストすること |
| アクセストークンの代わりに ID トークンを使用している | API 認証には ID トークンではなく アクセストークン を使用すること |
| 401/403 エラーを処理していない | 未認証・アクセス拒否レスポンスに対する適切なエラーハンドリングを実装すること |
auth0-quickstart — Auth0 の基本セットアップauth0-fastify — セッションを使用するサーバーサイドレンダリングの Fastify Web アプリ向けauth0-mfa — 多要素認証(MFA)の追加auth0-cli — ターミナルから Auth0 リソースを管理Plugin オプション:
domain — Auth0 テナントドメイン(必須)audience — Auth0 API 設定の API 識別子(必須)Request プロパティ:
request.user — デコードされた JWT クレームオブジェクトrequest.user.sub — ユーザー ID(subject)ミドルウェア:
fastify.requireAuth() — JWT 検証によるルートの保護fastify.requireAuth({ scopes: 'read:data' }) — 特定のスコープを要求fastify.requireAuth({ scopes: ['read:data', 'write:data'] }) — 複数の特定スコープを要求主なユースケース:
preHandler: fastify.requireAuth() を使用(手順 5 参照)request.user.subrequest.user['namespace/claim'] 経由でアクセスProtect Fastify API endpoints with JWT access token validation using @auth0/auth0-fastify-api.
auth0-quickstart skill first@auth0/auth0-fastify for session-based authauth0-react, auth0-vue, or auth0-angular for client-side authauth0-nextjs skillauth0-react-native for React Native/Exponpm install @auth0/auth0-fastify-api fastify dotenv
You need an API (not Application) in Auth0:
# Using Auth0 CLI
auth0 apis create \
--name "My Fastify API" \
--identifier https://my-api.example.com
Or create manually in Auth0 Dashboard → Applications → APIs
Create .env:
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_AUDIENCE=https://my-api.example.com
Create your Fastify server (server.js):
import 'dotenv/config';
import Fastify from 'fastify';
import fastifyAuth0Api from '@auth0/auth0-fastify-api';
const fastify = Fastify({ logger: true });
// Register Auth0 API plugin
await fastify.register(fastifyAuth0Api, {
domain: process.env.AUTH0_DOMAIN,
audience: process.env.AUTH0_AUDIENCE,
});
fastify.listen({ port: 3001 });
// Public route - no authentication
fastify.get('/api/public', async (request, reply) => {
return {
message: 'Hello from a public endpoint!',
timestamp: new Date().toISOString(),
};
});
// Protected route - requires valid JWT
fastify.get('/api/private', {
preHandler: fastify.requireAuth()
}, async (request, reply) => {
return {
message: 'Hello from a protected endpoint!',
user: request.user.sub,
timestamp: new Date().toISOString(),
};
});
// Protected route with user info
fastify.get('/api/profile', {
preHandler: fastify.requireAuth()
}, async (request, reply) => {
return {
profile: request.user, // JWT claims
};
});
Test public endpoint:
curl http://localhost:3001/api/public
Test protected endpoint (requires access token):
# First, obtain an access token (e.g. via Auth0 Dashboard > APIs > Test tab)
curl http://localhost:3001/api/private \
-H "Authorization: Bearer $ACCESS_TOKEN"
| Mistake | Fix |
|---|---|
| Created Application instead of API in Auth0 | Must create API resource in Auth0 Dashboard → Applications → APIs |
| Missing Authorization header | Include Authorization: Bearer <token> in all protected endpoint requests |
| Wrong audience in token | Client must request token with matching audience parameter |
| Using ID token instead of access token | Must use access token for API auth, not ID token |
| Not handling 401/403 errors | Implement proper error handling for unauthorized/forbidden responses |
auth0-quickstart - Basic Auth0 setupauth0-fastify - For server-rendered Fastify web apps with sessionsauth0-mfa - Add Multi-Factor Authenticationauth0-cli - Manage Auth0 resources from the terminalPlugin Options:
domain - Auth0 tenant domain (required)audience - API identifier from Auth0 API settings (required)Request Properties:
request.user - Decoded JWT claims objectrequest.user.sub - User ID (subject)Middleware:
fastify.requireAuth() - Protect route with JWT validationfastify.requireAuth({ scopes: 'read:data' }) - Require specific scopefastify.requireAuth({ scopes: ['read:data', 'write:data'] }) - Require specific scopesCommon Use Cases:
preHandler: fastify.requireAuth() (see Step 5)request.user.subrequest.user['namespace/claim']原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。