用途
auth0-fastify-api 用于保护 Fastify API 端点,通过 JWT 访问令牌验证实现对 API 的鉴权。它集成了 @auth0/auth0-fastify-api,适用于接收…的无状态 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 Dashboard → Applications → APIs 中手动创建。
3. 配置环境变量
创建 .env:
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_AUDIENCE=https://my-api.example.com
4. 配置 Auth 插件
创建 Fastify 服务器(server.js):
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. 保护路由
// 公开路由 - 无需认证
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 claims
};
});
6. 测试 API
测试公开端点:
curl http://localhost:3001/api/public
测试受保护端点(需要访问令牌):
# 首先获取访问令牌(例如通过 Auth0 Dashboard > APIs > Test 标签页)
curl http://localhost:3001/api/private \
-H "Authorization: Bearer $ACCESS_TOKEN"
常见错误与修复
- 在 Auth0 中创建了 Application 而非 API:必须在 Auth0 Dashboard → Applications → APIs 中创建 API 资源。
- 缺少 Authorization 头:在所有受保护端点请求中包含 Authorization: Bearer <token>。
- 令牌中 audience 错误:客户端必须使用匹配的 audience 参数请求令牌。
- 使用 ID token 而非 access token:API 鉴权必须使用访问令牌,而非 ID 令牌。
- 未处理 401/403 错误:为未授权/禁止响应实现适当的错误处理。
相关技能
- auth0-quickstart - 基础 Auth0 设置
- auth0-fastify - 用于带会话的服务端渲染 Fastify Web 应用
- auth0-mfa - 添加多因素认证
- auth0-cli - 从终端管理 Auth0 资源
快速参考
插件选项:
- domain - Auth0 租户域名(必填)
- audience - Auth0 API 设置中的 API 标识符(必填)
请求属性:
- request.user - 解码后的 JWT 声明对象
- request.user.sub - 用户 ID(subject)
中间件:
- fastify.requireAuth() - 使用 JWT 验证保护路由
- fastify.requireAuth({ scopes: 'read:data' }) - 要求特定 scope
- fastify.requireAuth({ scopes: ['read:data', 'write:data'] }) - 要求特定多个 scope
常见用例:
- 保护路由 → 使用 preHandler: fastify.requireAuth()(见第 5 步)
- 获取用户 ID → request.user.sub
- 自定义声明 → 通过 request.user['namespace/claim'] 访问
参考资料
- Auth0 Fastify API Documentation
- SDK GitHub Repository
- Access Tokens Guide
限制
资料未提供该技能的收费、价格、性能或其他未明确列出的信息。使用前请确保满足上述前置条件,并注意不适用于服务端渲染 Web 应用、单页应用、Next.js 和移动应用等场景。