auth0-fastify-api

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Auth0 Fastify API Integration

Auth0 Fastify API 集成

Protect Fastify API endpoints with JWT access token validation using @auth0/auth0-fastify-api.

使用@auth0/auth0-fastify-api通过JWT访问令牌验证来保护Fastify API端点。

Prerequisites

前置条件

  • Fastify API application (v5.x or newer)
  • Node.js 20 LTS or newer
  • Auth0 API configured (not Application - must be API resource)
  • If you don't have Auth0 set up yet, use the
    auth0-quickstart
    skill first
  • Fastify API应用(v5.x或更高版本)
  • Node.js 20 LTS或更高版本
  • 已配置的Auth0 API(注意:不是应用程序,必须是API资源)
  • 如果还未设置Auth0,请先使用
    auth0-quickstart
    技能

When NOT to Use

不适用场景

  • Server-rendered web applications - Use
    @auth0/auth0-fastify
    for session-based auth
  • Single Page Applications - Use
    auth0-react
    ,
    auth0-vue
    , or
    auth0-angular
    for client-side auth
  • Next.js applications - Use
    auth0-nextjs
    skill
  • Mobile applications - Use
    auth0-react-native
    for React Native/Expo

  • 服务端渲染的Web应用 - 如需基于会话的认证,请使用
    @auth0/auth0-fastify
  • 单页应用(SPA) - 客户端认证请使用
    auth0-react
    auth0-vue
    auth0-angular
  • Next.js应用 - 使用
    auth0-nextjs
    技能
  • 移动应用 - React Native/Expo应用请使用
    auth0-react-native

Quick Start Workflow

快速开始流程

1. Install SDK

1. 安装SDK

bash
npm install @auth0/auth0-fastify-api fastify dotenv
bash
npm install @auth0/auth0-fastify-api fastify dotenv

2. Create Auth0 API

2. 创建Auth0 API

You need an API (not Application) in Auth0:
bash
undefined
你需要在Auth0中创建一个API(而非应用程序):
bash
undefined

Using Auth0 CLI

使用Auth0 CLI

auth0 apis create
--name "My Fastify API"
--identifier https://my-api.example.com

Or create manually in Auth0 Dashboard → Applications → APIs
auth0 apis create
--name "My Fastify API"
--identifier https://my-api.example.com

或在Auth0控制台手动创建:应用程序 → APIs

3. Configure Environment

3. 配置环境变量

Create
.env
:
bash
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_AUDIENCE=https://my-api.example.com
创建
.env
文件:
bash
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_AUDIENCE=https://my-api.example.com

4. Configure Auth Plugin

4. 配置认证插件

Create your Fastify server (
server.js
):
javascript
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 });
创建Fastify服务器(
server.js
):
javascript
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. Protect Routes

5. 保护路由

javascript
// 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
  };
});
javascript
// 公开路由 - 无需认证
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声明
  };
});

6. Test API

6. 测试API

Test public endpoint:
bash
curl http://localhost:3001/api/public
Test protected endpoint (requires access token):
bash
curl http://localhost:3001/api/private \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

测试公开端点:
bash
curl http://localhost:3001/api/public
测试受保护端点(需要访问令牌):
bash
curl http://localhost:3001/api/private \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Common Mistakes

常见错误

MistakeFix
Created Application instead of API in Auth0Must create API resource in Auth0 Dashboard → Applications → APIs
Missing Authorization headerInclude
Authorization: Bearer <token>
in all protected endpoint requests
Wrong audience in tokenClient must request token with matching
audience
parameter
Using ID token instead of access tokenMust use access token for API auth, not ID token
Not handling 401/403 errorsImplement proper error handling for unauthorized/forbidden responses

错误修复方案
在Auth0中创建了应用程序而非API必须在Auth0控制台 → 应用程序 → APIs中创建API资源
缺少Authorization请求头在所有受保护端点的请求中包含
Authorization: Bearer <token>
令牌中的受众(audience)不匹配客户端请求令牌时必须使用匹配的
audience
参数
使用ID令牌而非访问令牌API认证必须使用访问令牌,而非ID令牌
未处理401/403错误为未授权/禁止访问的响应实现适当的错误处理

Related Skills

相关技能

  • auth0-quickstart
    - Basic Auth0 setup
  • auth0-fastify
    - For server-rendered Fastify web apps with sessions
  • auth0-mfa
    - Add Multi-Factor Authentication

  • auth0-quickstart
    - Auth0基础设置
  • auth0-fastify
    - 适用于带会话的服务端渲染Fastify Web应用
  • auth0-mfa
    - 添加多因素认证

Quick Reference

快速参考

Plugin Options:
  • domain
    - Auth0 tenant domain (required)
  • audience
    - API identifier from Auth0 API settings (required)
Request Properties:
  • request.user
    - Decoded JWT claims object
  • request.user.sub
    - User ID (subject)
Middleware:
  • fastify.requireAuth()
    - Protect route with JWT validation
  • fastify.requireAuth({ scopes: 'read:data' })
    - Require specific scope
  • fastify.requireAuth({ scopes: ['read:data', 'write:data'] })
    - Require specific scopes
Common Use Cases:
  • Protect routes → Use
    preHandler: fastify.requireAuth()
    (see Step 5)
  • Get user ID →
    request.user.sub
  • Custom claims → Access via
    request.user['namespace/claim']

插件选项:
  • 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']
    访问

References

参考资料