auth0-fastify

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Auth0 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
    auth0-quickstart
    skill first
  • Fastify应用(v5.x或更高版本)
  • Node.js 20 LTS或更高版本
  • 已配置的Auth0账号和应用
  • 若尚未设置Auth0,请先使用
    auth0-quickstart
    技能

When NOT to Use

不适用于以下场景

  • Single Page Applications - Use
    auth0-react
    ,
    auth0-vue
    , or
    auth0-angular
    for client-side auth
  • Next.js applications - Use
    auth0-nextjs
    skill which handles both client and server
  • Mobile applications - Use
    auth0-react-native
    for React Native/Expo
  • Stateless APIs - Use
    @auth0/auth0-fastify-api
    instead for JWT validation without sessions
  • Microservices - Use JWT validation for service-to-service auth

  • 单页应用 - 客户端认证请使用
    auth0-react
    auth0-vue
    auth0-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 dotenv
bash
npm install @auth0/auth0-fastify fastify @fastify/view ejs dotenv

2. Configure Environment

2. 配置环境变量

Create
.env
:
bash
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
Generate secret:
openssl rand -hex 64
创建
.env
文件:
bash
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. Configure Auth Plugin

3. 配置认证插件

Create your Fastify server (
server.js
):
javascript
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:
  • /auth/login
    - Login endpoint
  • /auth/logout
    - Logout endpoint
  • /auth/callback
    - OAuth callback
创建Fastify服务器文件(
server.js
):
javascript
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
    - 登出端点
  • /auth/callback
    - OAuth回调端点

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.js
Visit
http://localhost:3000
and test the login flow.

启动服务器:
bash
node server.js
访问
http://localhost:3000
并测试登录流程。

Common Mistakes

常见错误

MistakeFix
Forgot to add callback URL in Auth0 DashboardAdd
/auth/callback
path to Allowed Callback URLs (e.g.,
http://localhost:3000/auth/callback
)
Missing or weak SESSION_SECRETGenerate secure 64-char secret with
openssl rand -hex 64
and store in .env
App created as SPA type in Auth0Must be Regular Web Application type for server-side auth
Session secret exposed in codeAlways use environment variables, never hardcode secrets
Wrong appBaseUrl for productionUpdate APP_BASE_URL to match your production domain
Not awaiting fastify.registerFastify v4+ requires awaiting plugin registration

错误修复方案
忘记在Auth0控制台添加回调URL
/auth/callback
路径添加到允许的回调URL中(例如:
http://localhost:3000/auth/callback
缺少SESSION_SECRET或密钥强度不足使用
openssl rand -hex 64
生成64位安全密钥并存储在.env文件中
Auth0中应用类型创建为SPA服务端认证必须使用“常规Web应用”类型
会话密钥在代码中暴露始终使用环境变量存储密钥,切勿硬编码
生产环境中APP_BASE_URL设置错误更新APP_BASE_URL以匹配你的生产域名
未使用await调用fastify.registerFastify v4+要求插件注册必须使用await

Related Skills

相关技能

  • auth0-quickstart
    - Basic Auth0 setup
  • auth0-migration
    - Migrate from another auth provider
  • auth0-mfa
    - Add Multi-Factor Authentication

  • auth0-quickstart
    - Auth0基础设置
  • auth0-migration
    - 从其他认证提供商迁移
  • auth0-mfa
    - 添加多因素认证

Quick Reference

快速参考

Plugin Options:
  • domain
    - Auth0 tenant domain (required)
  • clientId
    - Auth0 client ID (required)
  • clientSecret
    - Auth0 client secret (required)
  • appBaseUrl
    - Application URL (required)
  • sessionSecret
    - Session encryption secret (required, min 64 chars)
  • audience
    - API audience (optional, for calling APIs)
Client Methods:
  • fastify.auth0Client.getSession({ request, reply })
    - Get user session
  • fastify.auth0Client.getUser({ request, reply })
    - Get user profile
  • fastify.auth0Client.getAccessToken({ request, reply })
    - Get access token
  • fastify.auth0Client.logout(options, { request, reply })
    - Logout user
Common Use Cases:
  • Protected routes → Use
    preHandler
    to check session (see Step 4)
  • Check auth status →
    !!session
  • Get user info →
    getUser({ request, reply })
  • Call APIs →
    getAccessToken({ request, reply })

插件选项:
  • 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 })

References

参考链接