auth0-fastify-api
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAuth0 Fastify API Integration
Auth0 Fastify API 集成
Protect Fastify API endpoints with JWT access token validation using @auth0/auth0-fastify-api.
使用@auth0/auth0-fastify-api通过JWT访问令牌验证来保护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 skill first
auth0-quickstart
- Fastify API应用(v5.x或更高版本)
- Node.js 20 LTS或更高版本
- 已配置的Auth0 API(注意:不是应用程序,必须是API资源)
- 如果还未设置Auth0,请先使用技能
auth0-quickstart
When NOT to Use
不适用场景
- Server-rendered web applications - Use for session-based auth
@auth0/auth0-fastify - Single Page Applications - Use ,
auth0-react, orauth0-vuefor client-side authauth0-angular - Next.js applications - Use skill
auth0-nextjs - Mobile applications - Use for React Native/Expo
auth0-react-native
- 服务端渲染的Web应用 - 如需基于会话的认证,请使用
@auth0/auth0-fastify - 单页应用(SPA) - 客户端认证请使用、
auth0-react或auth0-vueauth0-angular - Next.js应用 - 使用技能
auth0-nextjs - 移动应用 - React Native/Expo应用请使用
auth0-react-native
Quick Start Workflow
快速开始流程
1. Install SDK
1. 安装SDK
bash
npm install @auth0/auth0-fastify-api fastify dotenvbash
npm install @auth0/auth0-fastify-api fastify dotenv2. Create Auth0 API
2. 创建Auth0 API
You need an API (not Application) in Auth0:
bash
undefined你需要在Auth0中创建一个API(而非应用程序):
bash
undefinedUsing Auth0 CLI
使用Auth0 CLI
Or create manually in Auth0 Dashboard → Applications → APIs
或在Auth0控制台手动创建:应用程序 → APIs3. Configure Environment
3. 配置环境变量
Create :
.envbash
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_AUDIENCE=https://my-api.example.com创建文件:
.envbash
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_AUDIENCE=https://my-api.example.com4. Configure Auth Plugin
4. 配置认证插件
Create your Fastify server ():
server.jsjavascript
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 });创建Fastify服务器():
server.jsjavascript
import 'dotenv/config';
import Fastify from 'fastify';
import fastifyAuth0Api from '@auth0/auth0-fastify-api';
const fastify = Fastify({ logger: true });
// 注册Auth0 API插件
await fastify.register(fastifyAuth0Api, {
domain: process.env.AUTH0_DOMAIN,
audience: process.env.AUTH0_AUDIENCE,
});
fastify.listen({ port: 3001 });5. Protect Routes
5. 保护路由
javascript
// 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
};
});javascript
// 公开路由 - 无需认证
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. Test API
6. 测试API
Test public endpoint:
bash
curl http://localhost:3001/api/publicTest protected endpoint (requires access token):
bash
curl http://localhost:3001/api/private \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"测试公开端点:
bash
curl http://localhost:3001/api/public测试受保护端点(需要访问令牌):
bash
curl http://localhost:3001/api/private \
-H "Authorization: Bearer YOUR_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 |
| Wrong audience in token | Client must request token with matching |
| 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中创建了应用程序而非API | 必须在Auth0控制台 → 应用程序 → APIs中创建API资源 |
| 缺少Authorization请求头 | 在所有受保护端点的请求中包含 |
| 令牌中的受众(audience)不匹配 | 客户端请求令牌时必须使用匹配的 |
| 使用ID令牌而非访问令牌 | API认证必须使用访问令牌,而非ID令牌 |
| 未处理401/403错误 | 为未授权/禁止访问的响应实现适当的错误处理 |
Related Skills
相关技能
- - Basic Auth0 setup
auth0-quickstart - - For server-rendered Fastify web apps with sessions
auth0-fastify - - Add Multi-Factor Authentication
auth0-mfa
- - Auth0基础设置
auth0-quickstart - - 适用于带会话的服务端渲染Fastify Web应用
auth0-fastify - - 添加多因素认证
auth0-mfa
Quick Reference
快速参考
Plugin Options:
- - Auth0 tenant domain (required)
domain - - API identifier from Auth0 API settings (required)
audience
Request Properties:
- - Decoded JWT claims object
request.user - - User ID (subject)
request.user.sub
Middleware:
- - Protect route with JWT validation
fastify.requireAuth() - - Require specific scope
fastify.requireAuth({ scopes: 'read:data' }) - - Require specific scopes
fastify.requireAuth({ scopes: ['read:data', 'write:data'] })
Common Use Cases:
- Protect routes → Use (see Step 5)
preHandler: fastify.requireAuth() - Get user ID →
request.user.sub - Custom claims → Access via
request.user['namespace/claim']
插件选项:
- - Auth0租户域名(必填)
domain - - 来自Auth0 API设置的API标识符(必填)
audience
请求属性:
- - 解码后的JWT声明对象
request.user - - 用户ID(主题)
request.user.sub
中间件:
- - 使用JWT验证保护路由
fastify.requireAuth() - - 要求特定权限范围
fastify.requireAuth({ scopes: 'read:data' }) - - 要求多个特定权限范围
fastify.requireAuth({ scopes: ['read:data', 'write:data'] })
常见使用场景:
- 保护路由 → 使用(见步骤5)
preHandler: fastify.requireAuth() - 获取用户ID →
request.user.sub - 自定义声明 → 通过访问
request.user['namespace/claim']