@fastify/auth

中文文档
5.1.2发布于 2026/10/09MITTypeScriptCommonJS构建来源已验证近 30 天下载 64.4万

在 Fastify 中运行多个认证函数

中文使用文档
文档目录9 节
  1. 安装
  2. 兼容性
  3. 使用量
  4. 安全考虑
  5. 钩选择
  6. API 密码
  7. 选项
  8. 承认
  9. 许可证

@ fastify/ auth (帮助)

CI NPM version neostandard javascript style

本模块不提供认证策略,而是在不增加间接费用的情况下快速用于处理路由中的认证和多策略. 见一个完整的例子 这里。 。 。 .

安装

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 政策 更多细节.

使用量

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

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

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 也可以使用:

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)]可以用以下代码实现:

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数字 :

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

更多实例请检查 example-composited.js

此插件支持 callbacks 和 Promises 按函数返回。 说明a async 函数 没有 来呼叫 done 参数, 否则, 路由处理器会链接到认证方法 可能会被多次调用数字 :

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' })
      }
    })
  })

路线定义应作为 一个插件 或在内 .after() 调用。 完整的例子见 实例.js。 。 。 .

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

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 钩:

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 勾通运行当前插件中的所有路由及其后代的认证.

安全考虑

钩选择

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

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

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

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

API 密码

选项

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

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

承认

过去提案国:

  • 莱兹

许可证

许可证根据 麻省理工学院。 。 。 .

版本与发布记录

@fastify/auth 共发布 22 个版本,首次发布于 2022/04/27;过去 12 个月发布了 4 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
5.1.2latest2026/10/091 个月前
5.1.12026/09/161 个月前
5.1.02026/08/083 个月前
5.0.42025/11/2811 个月前
5.0.32025/09/281.1 年前
5.0.22024/12/141.9 年前

其他发布通道:next → 5.0.0。

关于 @fastify/auth 的常见问题

@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 和提交记录判断。