auth0-fastify
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAuth0 Fastify Integration
Auth0 Fastify 集成
Add authentication to Fastify web applications using @auth0/auth0-fastify.
使用@auth0/auth0-fastify为Fastify Web应用添加认证功能。
Prerequisites
前置条件
- Fastify application (v5.x or newer)
- Node.js 20 LTS or newer
- Auth0 account and application configured
- If you don't have Auth0 set up yet, use the skill first
auth0-quickstart
- Fastify应用(v5.x或更高版本)
- Node.js 20 LTS或更高版本
- 已配置的Auth0账号和应用
- 若尚未设置Auth0,请先使用技能
auth0-quickstart
When NOT to Use
不适用于以下场景
- Single Page Applications - Use ,
auth0-react, orauth0-vuefor client-side authauth0-angular - Next.js applications - Use skill which handles both client and server
auth0-nextjs - Mobile applications - Use for React Native/Expo
auth0-react-native - Stateless APIs - Use instead for JWT validation without sessions
@auth0/auth0-fastify-api - Microservices - Use JWT validation for service-to-service auth
- 单页应用 - 客户端认证请使用、
auth0-react或auth0-vueauth0-angular - Next.js应用 - 请使用技能,它可同时处理客户端和服务端认证
auth0-nextjs - 移动应用 - React Native/Expo应用请使用
auth0-react-native - 无状态API - 如需无会话的JWT验证,请使用替代
@auth0/auth0-fastify-api - 微服务 - 服务间认证请使用JWT验证
Quick Start Workflow
快速开始流程
1. Install SDK
1. 安装SDK
bash
npm install @auth0/auth0-fastify fastify @fastify/view ejs dotenvbash
npm install @auth0/auth0-fastify fastify @fastify/view ejs dotenv2. Configure Environment
2. 配置环境变量
Create :
.envbash
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:3000Generate secret:
openssl rand -hex 64创建文件:
.envbash
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 643. Configure Auth Plugin
3. 配置认证插件
Create your Fastify server ():
server.jsjavascript
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 });This automatically creates:
- - Login endpoint
/auth/login - - Logout endpoint
/auth/logout - - OAuth callback
/auth/callback
创建Fastify服务器文件():
server.jsjavascript
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 });
// 注册视图引擎
await fastify.register(fastifyView, {
engine: { ejs },
root: './views',
});
// 配置Auth0插件
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 - - OAuth回调端点
/auth/callback
4. Add Routes
4. 添加路由
javascript
// 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 });
});javascript
// 公开路由
fastify.get('/', async (request, reply) => {
const session = await fastify.auth0Client.getSession({ request, reply });
return reply.view('views/home.ejs', {
isAuthenticated: !!session,
});
});
// 受保护路由
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. Test Authentication
5. 测试认证功能
Start your server:
bash
node server.jsVisit and test the login flow.
http://localhost:3000启动服务器:
bash
node server.js访问并测试登录流程。
http://localhost:3000Common Mistakes
常见错误
| Mistake | Fix |
|---|---|
| Forgot to add callback URL in Auth0 Dashboard | Add |
| Missing or weak SESSION_SECRET | Generate secure 64-char secret with |
| App created as SPA type in Auth0 | Must be Regular Web Application type for server-side auth |
| Session secret exposed in code | Always use environment variables, never hardcode secrets |
| Wrong appBaseUrl for production | Update APP_BASE_URL to match your production domain |
| Not awaiting fastify.register | Fastify v4+ requires awaiting plugin registration |
| 错误 | 修复方案 |
|---|---|
| 忘记在Auth0控制台添加回调URL | 将 |
| 缺少SESSION_SECRET或密钥强度不足 | 使用 |
| Auth0中应用类型创建为SPA | 服务端认证必须使用“常规Web应用”类型 |
| 会话密钥在代码中暴露 | 始终使用环境变量存储密钥,切勿硬编码 |
| 生产环境中APP_BASE_URL设置错误 | 更新APP_BASE_URL以匹配你的生产域名 |
| 未使用await调用fastify.register | Fastify v4+要求插件注册必须使用await |
Related Skills
相关技能
- - Basic Auth0 setup
auth0-quickstart - - Migrate from another auth provider
auth0-migration - - Add Multi-Factor Authentication
auth0-mfa
- - Auth0基础设置
auth0-quickstart - - 从其他认证提供商迁移
auth0-migration - - 添加多因素认证
auth0-mfa
Quick Reference
快速参考
Plugin Options:
- - Auth0 tenant domain (required)
domain - - Auth0 client ID (required)
clientId - - Auth0 client secret (required)
clientSecret - - Application URL (required)
appBaseUrl - - Session encryption secret (required, min 64 chars)
sessionSecret - - API audience (optional, for calling APIs)
audience
Client Methods:
- - Get user session
fastify.auth0Client.getSession({ request, reply }) - - Get user profile
fastify.auth0Client.getUser({ request, reply }) - - Get access token
fastify.auth0Client.getAccessToken({ request, reply }) - - Logout user
fastify.auth0Client.logout(options, { request, reply })
Common Use Cases:
- Protected routes → Use to check session (see Step 4)
preHandler - Check auth status →
!!session - Get user info →
getUser({ request, reply }) - Call APIs →
getAccessToken({ request, reply })
插件选项:
- - Auth0租户域名(必填)
domain - - Auth0客户端ID(必填)
clientId - - Auth0客户端密钥(必填)
clientSecret - - 应用URL(必填)
appBaseUrl - - 会话加密密钥(必填,至少64字符)
sessionSecret - - API受众(可选,用于调用API)
audience
客户端方法:
- - 获取用户会话
fastify.auth0Client.getSession({ request, reply }) - - 获取用户资料
fastify.auth0Client.getUser({ request, reply }) - - 获取访问令牌
fastify.auth0Client.getAccessToken({ request, reply }) - - 用户登出
fastify.auth0Client.logout(options, { request, reply })
常见使用场景:
- 受保护路由 → 使用检查会话(见步骤4)
preHandler - 检查认证状态 →
!!session - 获取用户信息 →
getUser({ request, reply }) - 调用API →
getAccessToken({ request, reply })