关于 auth0-fastify-api
为 Fastify API 集成 Auth0 JWT 验证的技能,面向构建受保护 API 的开发者。内容涵盖令牌验证、路由保护及作用域检查。
主要功能
- 01验证 JWT 访问令牌
- 02保护 API 路由
- 03检查令牌作用域
- 04读取用户声明
适用场景
- 01为私有 API 端点添加认证
- 02按作用域限制路由访问
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ auth0/ agent-skills --skill auth0-fastify-api安装后在 Claude Code 中输入/auth0-fastify-api确认已加载。
详细介绍
Auth0 Fastify API 集成
使用 @auth0/auth0-fastify-api 验证 JWT 访问令牌,保护 Fastify API 端点。
先决条件
- Fastify API 应用(v5.x 或更高版本)
- Node.js 20 LTS 或更高版本
- 已配置 Auth0 API(必须是 API 资源,而不是 Application)
- 如果尚未设置 Auth0,请先使用
auth0-quickstartskill
不适用场景
- 服务器渲染的 Web 应用 - 使用
@auth0/auth0-fastify实现基于会话的身份验证 - 单页应用 - 使用
auth0-react、auth0-vue或auth0-angular实现客户端身份验证 - Next.js 应用 - 使用
auth0-nextjsskill - 移动应用 - 使用
auth0-react-native支持 React Native/Expo
快速入门工作流
1. 安装 SDK
npm install @auth0/auth0-fastify-api fastify dotenv
2. 创建 Auth0 API
你需要在 Auth0 中创建 API(而不是 Application):
# Using 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. 配置身份验证插件
创建 Fastify 服务(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. 保护路由
// 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. 测试 API
测试公共端点:
curl http://localhost:3001/api/public
测试受保护的端点(需要访问令牌):
# First, obtain an access token (e.g. via Auth0 Dashboard > APIs > Test tab)
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 令牌而不是访问令牌 | 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(主体)
中间件:
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']访问
参考资料
评论
支持 Markdown