关于 auth0-fastify
为 Fastify Web 应用集成 Auth0 会话认证的技能,面向需要登录流程的服务端渲染应用开发者。它介绍 OAuth 回调、会话管理及受保护路由。
主要功能
- 01配置 Auth0 认证插件
- 02提供登录与登出端点
- 03获取会话和用户资料
- 04为路由添加会话保护
- 05获取访问令牌
适用场景
- 01为 Fastify 网站实现登录流程
- 02限制未登录用户访问路由
- 03在会话中读取用户资料
- 04使用访问令牌调用 API
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ auth0/ agent-skills --skill auth0-fastify安装后在 Claude Code 中输入/auth0-fastify确认已加载。
详细介绍
Auth0 Fastify 集成
使用 @auth0/auth0-fastify 为 Fastify Web 应用添加身份验证。
前置条件
- Fastify 应用(v5.x 或更高版本)
- Node.js 20 LTS 或更高版本
- 已配置的 Auth0 账户和应用
- 如果尚未设置 Auth0,请先使用
auth0-quickstart技能
不适用场景
- 单页应用 - 客户端身份验证请使用
auth0-react、auth0-vue或auth0-angular - Next.js 应用 - 使用
auth0-nextjs技能,它同时处理客户端和服务器端 - 移动应用 - React Native/Expo 请使用
auth0-react-native - 无状态 API - 如需在没有会话的情况下验证 JWT,请改用
@auth0/auth0-fastify-api - 微服务 - 服务间身份验证请使用 JWT 验证
快速入门工作流
1. 安装 SDK
npm install @auth0/auth0-fastify fastify @fastify/view ejs dotenv
2. 配置环境
创建 .env:
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_CLIENT_ID=your-client-id
AUTH0_CLIENT_SECRET=your-client-secret
SESSION_SECRET=<openssl-rand-hex-64>
APP_BASE_URL=http://localhost:3000
生成密钥:openssl rand -hex 64
3. 配置身份验证插件
创建 Fastify 服务(server.js):
import 'dotenv/config';
import Fastify from 'fastify';
import fastifyAuth0 from '@auth0/auth0-fastify';
import fastifyView from '@fastify/view';
import ejs from 'ejs';
const fastify = Fastify({ logger: true });
// Register view engine
await fastify.register(fastifyView, {
engine: { ejs },
root: './views',
});
// Configure Auth0 plugin
await fastify.register(fastifyAuth0, {
domain: process.env.AUTH0_DOMAIN,
clientId: process.env.AUTH0_CLIENT_ID,
clientSecret: process.env.AUTH0_CLIENT_SECRET,
appBaseUrl: process.env.APP_BASE_URL,
sessionSecret: process.env.SESSION_SECRET,
});
fastify.listen({ port: 3000 });
这会自动创建:
/auth/login- 登录端点/auth/logout- 登出端点/auth/callback- OAuth 回调
4. 添加路由
// Public route
fastify.get('/', async (request, reply) => {
const session = await fastify.auth0Client.getSession({ request, reply });
return reply.view('views/home.ejs', {
isAuthenticated: !!session,
});
});
// Protected route
fastify.get('/profile', {
preHandler: async (request, reply) => {
const session = await fastify.auth0Client.getSession({ request, reply });
if (!session) {
return reply.redirect('/auth/login');
}
}
}, async (request, reply) => {
const user = await fastify.auth0Client.getUser({ request, reply });
return reply.view('views/profile.ejs', { user });
});
5. 测试身份验证
启动服务:
node server.js
访问 http://localhost:3000 并测试登录流程。
常见错误
| 错误 | 修复方法 |
|---|---|
| 忘记在 Auth0 Dashboard 中添加回调 URL | 将 /auth/callback 路径添加到 Allowed Callback URLs(例如,http://localhost:3000/auth/callback) |
| 缺少或强度不足的 SESSION_SECRET | 使用 openssl rand -hex 64 生成安全的 64 字符密钥,并将其存储在 .env 中 |
| 在 Auth0 中将应用创建为 SPA 类型 | 服务器端身份验证必须使用 Regular Web Application 类型 |
| 会话密钥暴露在代码中 | 始终使用环境变量,切勿将密钥硬编码 |
| 生产环境的 appBaseUrl 错误 | 更新 APP_BASE_URL,使其与生产域名一致 |
| 未等待 fastify.register | Fastify v4+ 要求等待插件注册完成 |
相关技能
auth0-quickstart- Auth0 基础设置auth0-migration- 从其他身份验证提供商迁移auth0-mfa- 添加多因素身份验证auth0-cli- 从终端管理 Auth0 资源
快速参考
插件选项:
domain- Auth0 租户域名(必需)clientId- Auth0 客户端 ID(必需)clientSecret- Auth0 客户端密钥(必需)appBaseUrl- 应用 URL(必需)sessionSecret- 会话加密密钥(必需,至少 64 个字符)audience- API 受众(可选,用于调用 API)
客户端方法:
fastify.auth0Client.getSession({ request, reply })- 获取用户会话fastify.auth0Client.getUser({ request, reply })- 获取用户资料fastify.auth0Client.getAccessToken({ request, reply })- 获取访问令牌fastify.auth0Client.logout(options, { request, reply })- 用户登出
常见用例:
- 受保护的路由 → 使用
preHandler检查会话(参见第 4 步) - 检查身份验证状态 →
!!session - 获取用户信息 →
getUser({ request, reply }) - 调用 API →
getAccessToken({ request, reply })
参考资料
评论
支持 Markdown