# @fastify/bearer-auth 中文文档

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

版本：10\.1\.4
npm 元数据更新时间：2026-10-18T12:30:29.903Z
中文译文更新时间：2026-11-14T11:22:29.958Z
软件包许可：MIT

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

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

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

- 包体积（解压后）：60.6 kB，25 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：2 个
- 首次发布：2022-04-21T21:17:35.302Z
- 最新版本发布：2026-10-08T11:20:34.686Z
- 近 30 天下载量：264266（2026-10-15 至 2026-11-13，npm 官方下载统计）
- 已发布版本数：22（近 12 个月 3 个）

## 中文简介

快速化的熊鼠认证插件

## 安装

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

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

## README

# @ fastify/ bearer-auth (英语)

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

_@ fastify/ bearer-auth (英语)_ 提供简单的 Bearer 认证请求钩钩 [快捷化](https://fastify.dev/) 网络框架.

## 安装

```
npm i @fastify/bearer-auth
```

### 兼容性

| 插件版本 | 快速化版本 |
| --- | --- |
| `^10.x` | `^5.x` |
| `^8.x` | `^4.x` |
| `^5.x` | `^3.x` |
| `^4.x` | `^2.x` |
| `^1.x` | `^1.x` |

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

## 示例

```js
'use strict'

const fastify = require('fastify')()
const bearerAuthPlugin = require('@fastify/bearer-auth')
const keys = new Set(['a-super-secret-key', 'another-super-secret-key'])

fastify.register(bearerAuthPlugin, {keys})
fastify.get('/foo', (req, reply) => {
  reply.send({authenticated: true})
})

fastify.listen({port: 8000}, (err) => {
  if (err) {
    fastify.log.error(err.message)
    process.exit(1)
  }
  fastify.log.info('http://127.0.0.1:8000/foo')
})
```

## API 密码

_@ fastify/ bearer-auth (英语)_ 导出标准 [快捷插件](https://github.com/fastify/fastify-plugin)。 。 。 . 这样可以将插件在范围化的路径中注册,因此可以保护一些路径 以插件表示,而其他的则不是。 见 [快捷化](https://fastify.dev/docs/latest/) 详细文件和实例.

注册插件时必须指定配置对象 :

-   `keys`页:1 `Set` 或带有有效类型密钥的数组 `string` (必须)
-   `function errorResponse (err) {}`: 方法必须同步返回内容正文 发送到客户端( 可选)
-   `contentType`: 如果要发送的内容是非 `application/json`,然后是 `contentType` 属性必须设置( 可选)
-   `bearerType`: 字符串指定熊鼠字符串(可选)
-   `specCompliance`数字 : 插件光谱遵守 。 接受一个 [`rfc6749`](https://datatracker.ietf.org/doc/html/rfc6749) 或者说 [`rfc6750`](https://datatracker.ietf.org/doc/html/rfc6750)。 。 。 . 默认为 `rfc6750`。 。 。 .
    -   `rfc6749` 是关于通用的 OAuth2.0 协议,允许符号类型对大小写不敏感
    -   `rfc6750` 是关于Bearer Token Usage的,它迫使符号类型是精确匹配的
-   `function auth (key, req) {}` : 此函数如果 `key` 是一个有效的符号。 它必须回来 `true` 被接受或 `false` 如果被拒绝。 函数还可以返回一个可以解决 至其中之一值。 如果函数返回或解决到任何其他值、拒绝或丢弃, hTTP 状态 `500` 将发送. `req` 是快捷请求对象。 若为 `auth` 是一个函数, `keys` 将被忽略。 若为 `auth` 不是一个函数或 `undefined`, (中文(简体) ), `keys` 将使用
-   `addHook`接受布尔, `'onRequest'`,或 `'preParsing'` (可选,默认为) `'onRequest'`:
    -   `true` 登记 a `onRequest` 钩子
    -   `'onRequest'` 财务报告和审定财务报表 `'preParsing'` 登记各自的钩子
    -   `false` 将不会注册一个钩子,和 `fastify.verifyBearerAuth` 财务报告和审定财务报表 `fastify.verifyBearerAuthFactory` 装饰器将被曝光
-   `verifyErrorLogLevel`: 指定用于校验错误的日志级的可选字符串. 它必须是由 Fastify 支持的有效日志级别,或者当 注册插件。 默认情况下,此选项将设定为 `error`

默认配置对象为:

```js
{
  keys: new Set(),
  contentType: undefined,
  bearerType: 'Bearer',
  specCompliance: 'rfc6750',
  errorResponse: (err) => {
    return {error: err.message}
  },
  auth: undefined,
  addHook: true
}
```

插件注册标准快取 [请求钩](https://github.com/fastify/fastify/blob/main/docs/Reference/Hooks.md#onrequest) 检查请求 一个 `authorization` 格式中的页眉 `bearer key`编辑 `key` 与 配置内容 `keys` 使用 a 对象 [恒定时间算法](https://en.wikipedia.org/wiki/Time_complexity) 预防 [时间攻击](https://snyk.io/blog/node-js-timing-attack-ccc-ctf/)如果 `authorization` 信头缺失、 格式不正确或 `key` 不验证, 401 个响应 与 `{error: message}` ,不进行进一步的请求处理.

## 与 `@fastify/auth`

此插件可以整合到 `@fastify/auth` 以此为例:

```js
const fastify = require('fastify')()
const auth = require('@fastify/auth')
const bearerAuthPlugin = require('@fastify/bearer-auth')
const keys = new Set(['a-super-secret-key', 'another-super-secret-key'])

async function server() {

  await fastify
    .register(auth)
    .register(bearerAuthPlugin, { addHook: false, keys, verifyErrorLogLevel: 'debug' })
    .decorate('allowAnonymous', function (req, reply, done) {
      if (req.headers.authorization) {
        return done(Error('not anonymous'))
      }
      return done()
    })

  fastify.route({
    method: 'GET',
    url: '/multiauth',
    preHandler: fastify.auth([
      fastify.allowAnonymous,
      fastify.verifyBearerAuth
    ]),
    handler: function (_, reply) {
      reply.send({ hello: 'world' })
    }
  })

  await fastify.listen({port: 8000})
}

server()
```

通过 `{ addHook: false }` 选项中 `verifyBearerAuth` 要引用的钩子 `done(someError)` 而不是立即对错误作出答复(`reply.send(someError)`) (中文(简体) ). 允许 `fastify.auth` 继续使用钩子列表中的下一个认证方案. 设置 `{ verifyErrorLogLevel: 'debug' }` 在选项中 `@fastify/bearer-auth` 发射 全部校验错误日志 `debug` 级别。 若为 `verifyBearerAuth` 是名单中最后一个钩子, `fastify.auth` 将答复 `Unauthorized`。 。 。 .

## 许可证

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

## 常见问题

### @fastify/bearer-auth 是什么？

快速化的熊鼠认证插件

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

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

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

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

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

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

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

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

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

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

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

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

