# @fastify/auth 中文文档

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

版本：5\.1\.2
npm 元数据更新时间：2026-10-18T12:30:26.821Z
中文译文更新时间：2026-11-14T11:19:03.852Z
软件包许可：MIT

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

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

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

- 包体积（解压后）：81.9 kB，20 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：2 个
- 首次发布：2022-04-27T13:30:37.517Z
- 最新版本发布：2026-10-09T11:15:44.303Z
- 近 30 天下载量：644208（2026-10-15 至 2026-11-13，npm 官方下载统计）
- 已发布版本数：22（近 12 个月 4 个）

## 中文简介

在 Fastify 中运行多个认证函数

## 安装

```sh
npm install @fastify/auth
```

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

## README

# @ fastify/ auth (帮助)

[![CI](https://github.com/fastify/fastify-auth/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-auth/actions/workflows/ci.yml) [![NPM version](https://img.shields.io/npm/v/@fastify/auth.svg?style=flat)](https://www.npmjs.com/package/@fastify/auth) [![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)

本模块不提供认证策略,而是在不增加间接费用的情况下快速用于处理路由中的认证和多策略. 见一个完整的例子 [这里](https://npmcn.com/package/%40fastify/auth/test/example.js)。 。 。 .

## 安装

```
npm i @fastify/auth
```

### 兼容性

| 插件版本 | 快速化版本 |
| --- | :-: |
| `>=5.x` | `^5.x` |
| `>=3.x <5.x` | `^4.x` |
| `>=1.x <3.x` | `^3.x` |
| `^0.x` | `^2.x` |
| `^0.x` | `^1.x` |

请注意,如果一个快取版本没有支持,那么该插件的相应版本也一样 上表列出. 见 [快速化 LTS 政策](https://github.com/fastify/fastify/blob/main/docs/Reference/LTS.md) 更多细节.

## 使用量

`@fastify/auth` 不提供认证策略; 认证策略必须使用装饰器或其他插件提供.

以下例子为显示本单元的使用提供了直接的实施:

```js
fastify
  .decorate('verifyJWTandLevel', function (request, reply, done) {
    // your validation logic
    done() // pass an error if the authentication fails
  })
  .decorate('verifyUserAndPassword', function (request, reply, done) {
    // your validation logic
    done() // pass an error if the authentication fails
  })
  .register(require('@fastify/auth'))
  .after(() => {
    fastify.route({
      method: 'POST',
      url: '/auth-multiple',
      preHandler: fastify.auth([
        fastify.verifyJWTandLevel,
        fastify.verifyUserAndPassword
      ]),
      handler: (req, reply) => {
        req.log.info('Auth route')
        reply.send({ hello: 'world' })
      }
    })
  })
```

这些定制认证策略的默认关系是: `or`不过 `and` 也可以使用:

```js
fastify
  .decorate('verifyAdmin', function (request, reply, done) {
    // your validation logic
    done() // pass an error if the authentication fails
  })
  .decorate('verifyReputation', function (request, reply, done) {
    // your validation logic
    done() // pass an error if the authentication fails
  })
  .register(require('@fastify/auth'))
  .after(() => {
    fastify.route({
      method: 'POST',
      url: '/auth-multiple',
      preHandler: fastify.auth([
        fastify.verifyAdmin,
        fastify.verifyReputation
      ], {
        relation: 'and'
      }),
      handler: (req, reply) => {
        req.log.info('Auth route')
        reply.send({ hello: 'world' })
      }
    })
  })
```

对于复合认证,如验证用户密码和级别或符合VIP标准,使用嵌入式阵列. 例如,逻辑\[(验证用户名词) `and` 校验等级) `or` (核查VIP)\]可以用以下代码实现:

```js
fastify
  .decorate('verifyUserPassword', function (request, reply, done) {
    // your validation logic
    done() // pass an error if the authentication fails
  })
  .decorate('verifyLevel', function (request, reply, done) {
    // your validation logic
    done() // pass an error if the authentication fails
  })
  .decorate('verifyVIP', function (request, reply, done) {
    // your validation logic
    done() // pass an error if the authentication fails
  })
  .register(require('@fastify/auth'))
  .after(() => {
    fastify.route({
      method: 'POST',
      url: '/auth-multiple',
      preHandler: fastify.auth([
        [fastify.verifyUserPassword, fastify.verifyLevel], // The arrays within an array have the opposite relation to the main (default) relation.
        fastify.verifyVIP
      ], {
        relation: 'or' // default relation
      }),
      handler: (req, reply) => {
        req.log.info('Auth route')
        reply.send({ hello: 'world' })
      }
    })
  })
```

如果 `relation` (单位:千美元)`defaultRelation`参数是 `and`,那么子阵列内部的关系将是 `or`。 。 。 . 如果 `relation` (单位:千美元)`defaultRelation`参数是 `or`,那么子阵列内部的关系将是 `and`。 。 。 .

| 认证代码 | 生成逻辑表达式 |
| --- | :-: |
| `fastify.auth([f1, f2, [f3, f4]], { relation: 'or' })` | `f1 OR f2 OR (f3 AND f4)` |
| `fastify.auth([f1, f2, [f3, f4]], { relation: 'and' })` | `f1 AND f2 AND (f3 OR f4)` |

这个 `defaultRelation` 选项可以在注册插件以更改默认值时使用 `relation`数字 :

```js
fastify.register(require('@fastify/auth'), { defaultRelation: 'and'} )
```

_更多实例请检查 [`example-composited.js`](https://npmcn.com/package/%40fastify/auth/test/example-composited.js)_

此插件支持 `callback`s 和 `Promise`s 按函数返回。 说明a `async` 函数 **没有** 来呼叫 `done` 参数, 否则, 路由处理器会链接到认证方法 [可能会被多次调用](https://fastify.dev/docs/latest/Reference/Hooks/#respond-to-a-request-from-a-hook)数字 :

```js
fastify
  .decorate('asyncVerifyJWTandLevel', async function (request, reply) {
    // your async validation logic
    await validation()
    // throws an error if the authentication fails
  })
  .decorate('asyncVerifyUserAndPassword', function (request, reply) {
    // return a promise that throws an error if the authentication fails
    return myPromiseValidation()
  })
  .register(require('@fastify/auth'))
  .after(() => {
    fastify.route({
      method: 'POST',
      url: '/auth-multiple',
      preHandler: fastify.auth([
        fastify.asyncVerifyJWTandLevel,
        fastify.asyncVerifyUserAndPassword
      ]),
      handler: (req, reply) => {
        req.log.info('Auth route')
        reply.send({ hello: 'world' })
      }
    })
  })
```

路线定义应作为 [一个插件](https://github.com/fastify/fastify/blob/main/docs/Reference/Plugins.md) 或在内 `.after()` 调用。 完整的例子见 [实例.js](https://npmcn.com/package/%40fastify/auth/test/example.js)。 。 。 .

`@fastify/auth` 运行所有认证方法,允许请求在至少一个成功的情况下继续;否则,它会返回一个错误给客户端. 任何成功的认证停止 `@fastify/auth` 不尝试其他的,除非 `run: 'all'` 提供参数:

```js
fastify.route({
  method: 'GET',
  url: '/run-all',
  preHandler: fastify.auth([
    (request, reply, done) => { console.log('executed 1'); done() },
    (request, reply, done) => { console.log('executed 2'); done() },
    (request, reply, done) => { console.log('executed 3'); done(new Error('you are not authenticated')) },
    (request, reply, done) => { console.log('executed 4'); done() },
    (request, reply, done) => { console.log('executed 5'); done(new Error('you shall not pass')) }
  ], { run: 'all' }),
  handler: (req, reply) => { reply.send({ hello: 'world' }) }
})
```

此示例显示所有控制台日志, 并总是以 `401: you are not authenticated`。 。 。 . 这个 `run` 参数用于将商业数据从认证符中读取到请求中.

此插件可以像上面的例子一样在路由级别使用,也可以在钩子级别使用 `preHandler` 钩:

```js
fastify.addHook('preHandler', fastify.auth([
  fastify.verifyJWTandLevel,
  fastify.verifyUserAndPassword
]))

fastify.route({
  method: 'POST',
  url: '/auth-multiple',
  handler: (req, reply) => {
    req.log.info('Auth route')
    reply.send({ hello: 'world' })
  }
})
```

这两种方法的不同之处在于使用路由级别 `preHandler` 函数只运行选定路由的认证,同时使用 `preHandler` 勾通运行当前插件中的所有路由及其后代的认证.

## 安全考虑

### 钩选择

在那个 [缩短使用周期](https://fastify.dev/docs/latest/Reference/Lifecycle/),则 `onRequest` 财务报告和审定财务报表 `preParsing` 级不剖析有效载荷,不同于 `preHandler` 阶段。 剖析身体可能是一种潜在的安全风险,因为它可用于拒绝服务(DoS)攻击. 因此,建议避免对尸体进行剖析,以便未经授权进入.

使用 `@fastify/auth` 插件在单元格中 `preHandler` 如果恶意用户在请求体中发送出一大笔有效载荷,且请求未经授权,钩子可能导致不必要的内存分配. 快速会解析身体,即使请求没有被授权,导致不必要的内存分配. 为了避免这种情况,请使用 `onRequest` 或者说 `preParsing` 如果该方法不需要请求正文, 则用于认证的钩子, 例如 `@fastify/jwt`,它期望在请求头中认证.

对于需要请求体的认证方法,如在请求体中发送一个符号,使用 `preHandler` 钩.

在混合情况下,您必须使用 `preHandler` 钩.

## API 密码

### 选项

_@ fastify/ auth (帮助)_ 接受选项对象 :

```js
{
  defaultRelation: 'and'
}
```

-   `defaultRelation` (默认 : `or`:函数之间的默认关系. 也可以这样 `or` 或者说 `and`。 。 。 .

## 承认

过去提案国:

-   莱兹

## 许可证

许可证根据 [麻省理工学院](https://npmcn.com/package/%40fastify/auth/LICENSE)。 。 。 .

## 常见问题

### @fastify/auth 是什么？

在 Fastify 中运行多个认证函数

### 如何安装 @fastify/auth？

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

### @fastify/auth 支持 TypeScript 吗？

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

### @fastify/auth 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @fastify/auth 可以商用吗？

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

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

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

### @fastify/auth 还在维护吗？

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

