🔐auth0-fastify-api
- プラグイン
- auth0
- ライセンス
- Apache-2.0
- ソース
- GitHub で見る ↗
説明
次のような場合に使用: JWT Bearerトークンのバリデーションやスコープチェックによって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.
ユースケース
- ✓JWT Bearerトークンを検証したいとき
- ✓APIエンドポイントのスコープをチェックするとき
- ✓ステートレスAPIを保護したいとき
- ✓フロントエンドからのアクセストークンを検証するとき
本文(日本語訳)
Auth0 Fastify API インテグレーション
@auth0/auth0-fastify-api を使用して、JWT アクセストークンの検証により Fastify API エンドポイントを保護します。
前提条件
- Fastify API アプリケーション(v5.x 以降)
- Node.js 20 LTS 以降
- Auth0 API の設定済み環境(Application ではなく API リソースであること)
- Auth0 をまだセットアップしていない場合は、先に
auth0-quickstartスキルを使用してください
使用しない場合
- サーバーサイドレンダリング Web アプリケーション — セッションベース認証には
@auth0/auth0-fastifyを使用 - シングルページアプリケーション(SPA) — クライアントサイド認証には
auth0-react、auth0-vue、またはauth0-angularを使用 - Next.js アプリケーション —
auth0-nextjsスキルを使用 - モバイルアプリケーション — React Native/Expo には
auth0-react-nativeを使用
クイックスタート手順
1. SDK のインストール
npm install @auth0/auth0-fastify-api fastify dotenv
2. Auth0 API の作成
Auth0 に API(Application ではなく)を作成します:
# Auth0 CLI を使用する場合
auth0 apis create \
--name "My Fastify API" \
--identifier https://my-api.example.com
または Auth0 ダッシュボード → Applications → APIs から手動で作成することもできます。
3. 環境変数の設定
.env を作成します:
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_AUDIENCE=https://my-api.example.com
4. Auth Plugin の設定
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 });
5. ルートの保護
// パブリックルート — 認証不要
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 クレーム
};
});
6. API のテスト
パブリックエンドポイントのテスト:
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 参照) - ユーザー ID の取得 →
request.user.sub - カスタムクレーム →
request.user['namespace/claim']経由でアクセス
参考リンク
原文(English)を表示
Auth0 Fastify API Integration
Protect Fastify API endpoints with JWT access token validation using @auth0/auth0-fastify-api.
Prerequisites
- Fastify API application (v5.x or newer)
- Node.js 20 LTS or newer
- Auth0 API configured (not Application - must be API resource)
- If you don't have Auth0 set up yet, use the
auth0-quickstartskill first
When NOT to Use
- Server-rendered web applications - Use
@auth0/auth0-fastifyfor session-based auth - Single Page Applications - Use
auth0-react,auth0-vue, orauth0-angularfor client-side auth - Next.js applications - Use
auth0-nextjsskill - Mobile applications - Use
auth0-react-nativefor React Native/Expo
Quick Start Workflow
1. Install SDK
npm install @auth0/auth0-fastify-api fastify dotenv
2. Create Auth0 API
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
3. Configure Environment
Create .env:
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_AUDIENCE=https://my-api.example.com
4. Configure Auth Plugin
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 });
5. Protect Routes
// 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
};
});
6. Test API
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"
Common Mistakes
| 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 |
Related Skills
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 terminal
Quick Reference
Plugin 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 scopes
Common Use Cases:
- Protect routes → Use
preHandler: fastify.requireAuth()(see Step 5) - Get user ID →
request.user.sub - Custom claims → Access via
request.user['namespace/claim']
References
原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。