# @fastify/basic-auth 中文文档

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

版本：6\.3\.1
npm 元数据更新时间：2026-10-18T12:30:29.282Z
中文译文更新时间：2026-11-14T11:17:55.629Z
软件包许可：MIT

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

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

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

- 包体积（解压后）：61.7 kB，14 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：2 个
- 首次发布：2022-04-27T13:32:16.943Z
- 最新版本发布：2026-10-09T14:47:43.026Z
- 近 30 天下载量：1060310（2026-10-15 至 2026-11-13，npm 官方下载统计）
- 已发布版本数：17（近 12 个月 2 个）

## 中文简介

简化基本认证插件

## 安装

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

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

## README

# @ fastify/ basic-auth (英语)

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

很简单 [基本认证](https://datatracker.ietf.org/doc/html/rfc7617) 快速化插件 .

## 安装

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

### 兼容性

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

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

## 使用量

此插件以一个 `basicAuth` 函数,可在路由处理器之前在任意钩子内使用,或与 [`@fastify/auth`](https://github.com/fastify/fastify-auth)。 。 。 .

```js
const fastify = require('fastify')()
const authenticate = {realm: 'Westeros'}
fastify.register(require('@fastify/basic-auth'), { validate, authenticate })
// `this` inside validate is `fastify`
function validate (username, password, req, reply, done) {
  if (username === 'Tyrion' && password === 'wine') {
    done()
  } else {
    done(new Error('Winter is coming'))
  }
}

fastify.after(() => {
  fastify.addHook('onRequest', fastify.basicAuth)

  fastify.get('/', (req, reply) => {
    reply.send({ hello: 'world' })
  })
})
```

承诺和 _自动/等待_ 也支持他们!

```js
const fastify = require('fastify')()
const authenticate = {realm: 'Westeros'}
fastify.register(require('@fastify/basic-auth'), { validate, authenticate })
async function validate (username, password, req, reply) {
  if (username !== 'Tyrion' || password !== 'wine') {
    return new Error('Winter is coming')
  }
}
```

使用方式 `onRequest`数字 :

```js
const fastify = require('fastify')()
const authenticate = {realm: 'Westeros'}
fastify.register(require('@fastify/basic-auth'), { validate, authenticate })
async function validate (username, password, req, reply) {
  if (username !== 'Tyrion' || password !== 'wine') {
    return new Error('Winter is coming')
  }
}

fastify.after(() => {
  fastify.route({
    method: 'GET',
    url: '/',
    onRequest: fastify.basicAuth,
    handler: async (req, reply) => {
      return { hello: 'world' }
    }
  })
})
```

使用方式 [`@fastify/auth`](https://github.com/fastify/fastify-auth)数字 :

```js
const fastify = require('fastify')()
const authenticate = {realm: 'Westeros'}
fastify.register(require('@fastify/auth'))
fastify.register(require('@fastify/basic-auth'), { validate, authenticate })
async function validate (username, password, req, reply) {
  if (username !== 'Tyrion' || password !== 'wine') {
    return new Error('Winter is coming')
  }
}

fastify.after(() => {
  // use preHandler to authenticate all the routes
  fastify.addHook('preHandler', fastify.auth([fastify.basicAuth]))

  fastify.route({
    method: 'GET',
    url: '/',
    // use onRequest to authenticate just this one
    onRequest: fastify.auth([fastify.basicAuth]),
    handler: async (req, reply) => {
      return { hello: 'world' }
    }
  })
})
```

### 自定义错误处理器

在认证失败时, `@fastify/basic-auth` 调用快捷键 [通用错误 处理器](https://fastify.dev/docs/latest/Reference/Server/#seterrorhandler) 错误 组合 `err.statusCode` 改为 `401`。 。 。 .

适当 `401` 错误 :

```js
fastify.setErrorHandler(function (err, req, reply) {
  if (err.statusCode === 401) {
    // This was unauthorized! Display the correct page/message
    reply.code(401).send({ was: 'unauthorized' })
    return
  }
  reply.send(err)
})
```

## 选项

### `utf8` (可选,默认:真实)

非美国ASCII字符的用户名或密码可能引起问题 除非双方就编码方案达成协议。 设置 `utf8` 改为 true 发送“ charset” 参数以选择“ UTF-8”, 增加 客户可能使用该编码.

### `strictCredentials` (可选,默认:真实)

设置 `strictCredentials` 允许在 授权标题的开头、中间和结尾. 这是一种倒置选项,用于确保行为与 `@fastify/basic-auth` <=-5.x.

### `validate` (必须)

这个 `validate` 每次请求时都会调用函数 并被传递 `username`, (中文(简体) ), `password`, (中文(简体) ), `req`,以及 `reply` 参数,按此顺序。 可选的第五个参数, `done`,可以是 用于在无论据的情况下请求有效 或无效的请求,如果 `Error` 对象。 或者, 页:1 `validate` 函数可以返回承诺, 解析是否有效 请求和拒绝无效。 这也可以使用 a 一个 `async/await` 函数,并显示无效请求.

例子见上文代码.

### `authenticate` < Boolean > 对象 > (可选,默认:虚假)

这个 `authenticate` 选项 [`WWW-Authenticate` 标题](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/WWW-Authenticate) 并可以设置 `realm` 数值.

这可以触发客户端认证接口,例如浏览器认证对话框.

设置 `authenticate` 改为 `true` 添加页眉 `WWW-Authenticate: Basic`时 `false`,不添加标题(默认).

何时 `proxyMode` 实值 `true` 它会使用 [`Proxy-Authenticate`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Proxy-Authenticate) 取而代之的是标题.

```js
fastify.register(require('@fastify/basic-auth'), {
  validate,
  authenticate: true // WWW-Authenticate: Basic
})

fastify.register(require('@fastify/basic-auth'), {
  validate,
  proxyMode: true,
  authenticate: true // Proxy-Authenticate: Basic
})

fastify.register(require('@fastify/basic-auth'), {
  validate,
  authenticate: false // no authenticate header, same as omitting authenticate option
})
```

这个 `authenticate` 选项 `realm` 键作为对象提供时. 如果 `realm` 键,将附加在标题值上:

```js
fastify.register(require('@fastify/basic-auth'), {
  validate,
  authenticate: {realm: 'example'} // WWW-Authenticate: Basic realm="example"
})
```

这个 `realm` 键也可以是函数 :

```js
fastify.register(require('@fastify/basic-auth'), {
  validate,
  authenticate: {
    realm(req) {
      return 'example' // WWW-Authenticate: Basic realm="example"
    }
  }
})
```

这个 `authenticate` 对象可以包括可选 `header` 键来自定义信头名称,替换默认 `WWW-Authenticate`数字 :

```js
fastify.register(require('@fastify/basic-auth'), {
  validate,
  authenticate: {
    header: 'Proxy-Authenticate' // Proxy-Authenticate: Basic
  }
})
```

### `proxyMode` 布尔( 可选, 默认: 假)

设置 `proxyMode` 改为 `true` 将执行插件 [HTTP 代理认证](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Authentication#proxy_authentication),而不是资源认证。 换言之,插件将:

-   读取 `Proxy-Authorization` 标题而不是 `Authorization`
-   使用情况 `407` 响应状态代码而不是 `401` 以指示缺少或无效的证书
-   使用该 `Proxy-Authenticate` 标题而不是 `WWW-Authenticate` 若为 `authenticate` 选项已设定

### `header` 字符串( 可选)

这个 `header` 选项指定要从认证中获取证书的页眉名称。 未指定则默认为 `Authorization` 或者说 `Proxy-Authorization` (根据 `proxyMode` 选项)

```js
fastify.register(require('@fastify/basic-auth'), {
  validate,
  header: 'x-forwarded-authorization'
})
```

## 许可证

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

## 常见问题

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

简化基本认证插件

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

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

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

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

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

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

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

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

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

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

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

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

