# @auth0/auth0-fastify 中文文档

规范地址：https://npmcn.com/package/%40auth0/auth0-fastify/

版本：1\.7\.0
npm 元数据更新时间：2026-10-26T15:21:11.426Z
中文译文更新时间：2026-11-07T05:56:36.890Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40auth0/auth0-fastify
原文对照：https://npmcn.com/package/%40auth0/auth0-fastify/?lang=original
项目主页：https://github.com/auth0/auth0-fastify#readme
源码仓库：https://github.com/auth0/auth0-fastify

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：113 kB，9 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：4 个
- 首次发布：2025-03-28T14:38:04.691Z
- 最新版本发布：2026-10-26T15:21:10.770Z
- 近 30 天下载量：12458（2026-10-07 至 2026-11-05，npm 官方下载统计）
- 已发布版本数：10（近 12 个月 5 个）

## 中文简介

在 JavaScript 运行时间上快速化应用程序的 Auth0 认证 SDK

## 安装

```sh
npm install @auth0/auth0-fastify
```

也可以使用：`pnpm add @auth0/auth0-fastify`、`yarn add @auth0/auth0-fastify`、`bun add @auth0/auth0-fastify`

## README

Auth0快取SDK是一个用于在快取应用程序中执行用户认证的库.

![Release](https://img.shields.io/npm/v/@auth0/auth0-fastify) ![Downloads](https://img.shields.io/npm/dw/@auth0/auth0-fastify) [![License](https://img.shields.io/:license-mit-blue.svg?style=flat)](https://opensource.org/licenses/MIT)

📚 [文档](https://npmcn.com/package/%40auth0/auth0-fastify/#readme-documentation) - 🔎 [特征](https://npmcn.com/package/%40auth0/auth0-fastify/#readme-features) - 🚀 [开始](https://npmcn.com/package/%40auth0/auth0-fastify/#readme-getting-started) - 💬 [反馈](https://npmcn.com/package/%40auth0/auth0-fastify/#readme-feedback)

## 文档

-   [实例](https://github.com/auth0/auth0-fastify/blob/main/packages/auth0-fastify/EXAMPLES.md) - 不同用法的例子.
-   [Docs 站点](https://auth0.com/docs) - 探索我们的文件网站 了解更多关于Auth0.

## 特征

直接跳到所需的能力.

| 特性 | 它会做什么 |
| --- | --- |
| [快开始](https://npmcn.com/package/%40auth0/auth0-fastify/#readme-getting-started) | 注册 Auth0 插件 `fastify.register` 数行 |
| [内建路线](https://npmcn.com/package/%40auth0/auth0-fastify/#readme-routes) | `/auth/login`, (中文(简体) ), `/auth/logout`, (中文(简体) ), `/auth/callback`后通道登录 |
| [自定义登录/ 登录/ 回调](https://npmcn.com/package/%40auth0/auth0-fastify/#readme-3-adding-login-and-logout) | 滚出自己的路线,而不是挂起的路线 |
| [配置挂载路线](https://npmcn.com/package/%40auth0/auth0-fastify/EXAMPLES.md#configuring-the-mounted-routes) | 禁用内置路由或添加账户链接路由 |
| [用会话保护路径](https://npmcn.com/package/%40auth0/auth0-fastify/#readme-4-protecting-routes) | 登录会话后面的门服务器已发送页面 |
| [获取当前会话/ 用户](https://npmcn.com/package/%40auth0/auth0-fastify/#readme-4-protecting-routes) | 使用 `getUser()` 编号 : `getSession()` |
| [调用 API (E)`getAccessToken`(中文(简体) )](https://npmcn.com/package/%40auth0/auth0-fastify/#readme-requesting-an-access-token-to-call-an-api) | 获取访问令牌, 将 API 调用为用户 |
| [密码](https://npmcn.com/package/%40auth0/auth0-fastify/EXAMPLES.md#login-and-signup-using-passkeys) | 签名用户并登录密码、电子邮件和电话核对码 |
| [自定义托肯交换](https://npmcn.com/package/%40auth0/auth0-fastify/EXAMPLES.md#login-using-custom-token-exchange) | 在没有浏览器登录的情况下从外部符号创建会话 |
| [通过会话传输进行假冒](https://npmcn.com/package/%40auth0/auth0-fastify/EXAMPLES.md#impersonation-via-session-transfer) | 将代理人作为客户登录到另一个应用程序,通过 `act` 索赔 |
| [多个自定义域( MCD)](https://npmcn.com/package/%40auth0/auth0-fastify/EXAMPLES.md#multiple-custom-domains-mcd) | 每个请求解决 Auth0 域 |
| [自定义 `fetch`](https://npmcn.com/package/%40auth0/auth0-fastify/EXAMPLES.md#configuring-a-customfetch-implementation) | 在自己获取中交换( 代理、 重试、 仪器) |
| [发现缓存](https://npmcn.com/package/%40auth0/auth0-fastify/EXAMPLES.md#discovery-cache) | 控制隐藏 OIDC 发现元数据和 JWKS |

## 开始

### 1\. 安装SDK

```shell
npm i @auth0/auth0-fastify
```

这个库需要Node.js 20 LTS和较新的LTS版本.

### 2\. 注册 Auth0 快捷插件

以快捷实例注册 Auth0 套接字 .

```ts
import auth0 from '@auth0/auth0-fastify';

fastify.register(auth0, {
  domain: '<AUTH0_DOMAIN>',
  clientId: '<AUTH0_CLIENT_ID>',
  clientSecret: '<AUTH0_CLIENT_SECRET>',
  appBaseUrl: '<APP_BASE_URL>',
  sessionSecret: '<SESSION_SECRET>'
});
```

这个 `AUTH0_DOMAIN`, (中文(简体) ), `AUTH0_CLIENT_ID`,以及 `AUTH0_CLIENT_SECRET` 可从 [Auth0 剪贴板](https://manage.auth0.com/) 一旦你创建了一个应用程序. **此申请必须是 `Regular Web Application`**。 。 。 .

这个 `SESSION_SECRET` 是用于加密会话 cookie 的密钥。 您可以使用 `openssl`数字 :

```shell
openssl rand -hex 64
```

这个 `APP_BASE_URL` 您的应用程序正在运行的 URL 。 本地开发时,这种情况最为常见 `http://localhost:3000`。 。 。 .

> \[大  
> 您需要在 Auth0 应用程序中通过 [Auth0 剪贴板](https://manage.auth0.com/)数字 :
> 
> -   添加 `http://localhost:3000/auth/callback` 名单 **允许召回 URL**
> -   添加 `http://localhost:3000` 名单 **允许登录 URL**

#### 路线

用于快速化网络应用的 SDK 搭载了4条主要路线:

1.  `/auth/login`: 用户将被重定向启动认证交易的登录路径. 支持添加一个 `returnTo` 登录后返回特定 URL 的查询字符串参数 。 它还转发a `session_transfer_token` 向 Auth0 查询字符串参数 `organization` 当该参数伴有STT时,此路由将双倍作为赎回端点 [通过会话传输进行假冒](https://npmcn.com/package/%40auth0/auth0-fastify/EXAMPLES.md#impersonation-via-session-transfer)。 。 。 .
2.  `/auth/logout`: 必须添加到您的 Auth0 应用程序允许的日志 URL 的日志路径
3.  `/auth/callback`: 必须在 Auth0 应用程序允许的回调 URL 中添加的回调路由
4.  `/auth/backchannel-logout`: 将接收到一个 `logout_token` 配置时 [后通道登录](https://auth0.com/docs/authenticate/login/logout/back-channel-logout) 启动发生

要禁用此行为, 您可以设置 `mountRoutes` 选项到 `false` (默认情况属实):

```ts
fastify.register(auth0, {
  mountRoutes: false
});
```

此外,通过设置 `mountConnectRoutes` 改为 `true` (默认是虚假的) SDK也可以挂载4条用于账户链接的路径:

1.  `/auth/connect`: 用户将重新定向以启动账户链接的路由
2.  `/auth/connect/callback`: 账户连接的回调路由, 该路由必须添加到您的 Auth0 应用程序的允许回调 URL
3.  `/auth/unconnect`: 用户将重新定向以启动账户链接的路由
4.  `/auth/unconnect/callback`: 账户连接的回调路由, 该路由必须添加到您的 Auth0 应用程序的允许回调 URL

> \[大  
> 何时 `mountRoutes` 设置为 `false`设置 `mountConnectRoutes` 没有效果.

### 3\. 添加登录和停用

当使用内置挂载路由时,用户可以被重定向到 `/auth/login` 启动登录流程,并 `/auth/logout` 以登录.

```html
<a href="/auth/logout">Log out</a>
<a href="/auth/login">Log in</a
>
```

在不使用内置路线时,您要给SDK打电话 `startInteractiveLogin()`, (中文(简体) ), `completeInteractiveLogin()` 财务报告和审定财务报表 `logout()` 方法:

```ts
fastify.get('/custom/login', async (request, reply) => {
  const authorizationUrl = await fastify.auth0Client.startInteractiveLogin(
    {
      authorizationParams: {
        // Custom URL to redirect back to after login to handle the callback.
        // Make sure to configure the URL in the Auth0 Dashboard as an Allowed Callback URL.
        redirect_uri: 'http://localhost:3000/custom/callback',
      }
    },
    { request, reply }
  );

  reply.redirect(authorizationUrl.href);
});


fastify.get('/custom/callback', async (request, reply) => {
  await fastify.auth0Client.completeInteractiveLogin(
    new URL(request.url, options.appBaseUrl),
    { request, reply }
  );

  reply.redirect('https://localhost:3000');
});

fastify.get('/custom/logout', async (request, reply) => {
  const logoutUrl = await auth0Client.logout({ returnTo: 'https://localhost:3000' }, { request, reply });

  reply.redirect(logoutUrl.href);
});
```

### 4\. 保护路线

为了保护快取路线,您可以使用 SDK 的 `getSession()` 自定义前汉德勒中的方法 :

```ts
async function hasSessionPreHandler(request: FastifyRequest, reply: FastifyReply) {
  const session = await fastify.auth0Client!.getSession({ request, reply });

  if (!session) {
    reply.redirect('/auth/login');
  }
}

fastify.get(
  '/profile',
  {
    preHandler: hasSessionPreHandler,
  },
  async (request, reply) => {
    const user = await fastify.auth0Client!.getUser({ request, reply });

    return reply.viewAsync('profile.ejs', {
      name: user!.name,
    });
  }
);
```

> \[大  
> 以上是通过会话保护服务器侧渲染路由,而不是使用无记名符号的API路由.

#### 请求访问托肯呼叫 API

如果您需要代表用户调用 API, 请指定 `audience` 参数用于注册插件。 这将使SDK在用户登录时为指定的受众请求访问令牌.

```ts
fastify.register(fastifyAuth0, {
  domain: '<AUTH0_DOMAIN>',
  clientId: '<AUTH0_CLIENT_ID>',
  clientSecret: '<AUTH0_CLIENT_SECRET>',
  audience: '<AUTH0_AUDIENCE>',
  appBaseUrl: '<APP_BASE_URL>',
  sessionSecret: '<SESSION_SECRET>',
});
```

这个 `AUTH0_AUDIENCE` 是您要调用的 API 的标识符。 您可以在 Auth0 仪表板的 API 部分中找到这个 .

通过使用 `getAccessToken`数字 :

```ts
const accessTokenResult = await fastify.auth0Client.getAccessToken({ request, reply });
console.log(accessTokenResult.accessToken);
```

## 反馈

### 捐款

我们赞赏反馈和对这次再投资的贡献! 在开始前,请阅读以下内容:

-   [Auth0的一般贡献准则](https://github.com/auth0/open-source-template/blob/master/GENERAL-CONTRIBUTING.md)
-   [Auth0 行为守则准则](https://github.com/auth0/open-source-template/blob/master/CODE-OF-CONDUCT.md)
-   [这个Repo的贡献指南](https://github.com/auth0/auth0-fastify/blob/main/CONTRIBUTING.md)

### 提出问题

请提供反馈或报告错误 [提出我们的问题追踪器](https://github.com/auth0/auth0-fastify/issues)。 。 。 .

## 脆弱性报告

请不要在公共 GitHub 问题跟踪器上报告安全漏洞 。 这个 [负责任的披露程序](https://auth0.com/responsible-disclosure-policy) 详细说明披露安全问题的程序.

## 什么是奥特?

![Auth0 Logo](https://cdn.auth0.com/website/sdks/logos/auth0_light_mode.png)

Auth0是一个易于执行,可适应的认证和授权平台. 学习更多退房 [为什么是Auth0?](https://auth0.com/why-auth0)

这个项目根据麻省理工学院的许可证获得许可。 见 [自由主义](https://github.com/auth0/auth0-fastify/blob/main/packages/auth0-fastify/LICENSE) 需要更多信息的文件.

## 常见问题

### @auth0/auth0-fastify 是什么？

在 JavaScript 运行时间上快速化应用程序的 Auth0 认证 SDK

### 如何安装 @auth0/auth0-fastify？

在项目目录运行 npm install @auth0/auth0-fastify，或使用 pnpm add / yarn add / bun add。

### @auth0/auth0-fastify 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @auth0/auth0-fastify 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @auth0/auth0-fastify 可以商用吗？

@auth0/auth0-fastify 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @auth0/auth0-fastify 的下载量有多少？

根据 npm 官方下载统计，@auth0/auth0-fastify 在 2026/10/07 – 2026/11/05 这 30 天内被下载 12,458 次，日均约 415 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @auth0/auth0-fastify 还在维护吗？

最新版本 1\.7\.0 发布于 2026/10/26（12 天前）；至今共发布 10 个版本，其中过去 12 个月发布了 5 个；首次发布于 2025/03/28。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

