百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
F

fastify-auth

> 安全
开源

在 Fastify 中运行多个认证函数

380 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

在 Fastify 中运行多个认证函数

@fastify/auth

This module does not provide an authentication strategy but offers a fast utility to handle authentication and multiple strategies in routes without adding overhead. See a complete example here.

Install

bash
npm i @fastify/auth

Compatibility

Plugin version Fastify version
>=5.x ^5.x
`>=3.x =1.x {
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' })
  }
})

})


The default relationship of these customized authentication strategies is `or`, but `and` can also be used:
```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' })
      }
    })
  })

For composite authentication, such as verifying user passwords and levels or meeting VIP criteria, use nested arrays. For example, the logic [(verifyUserPassword and verifyLevel) or (verifyVIP)] can be achieved with the following code:

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

…

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

For more examples, please check example-composited.js

This plugin supports callbacks and Promises returned by functions. Note that an async function does not have to call the done parameter, otherwise, the route handler linked to the auth methods might be called multiple times:

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

Route definition should be done as a plugin or within an .after() callback. For a complete example, see example.js.

@fastify/auth runs all authentication methods, allowing the request to continue if at least one succeeds; otherwise, it returns an error to the client. Any successful authentication stops @fastify/auth from trying the rest unless the run: 'all' parameter is provided:

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

This example shows all console logs and always replies with 401: you are not authenticated. The run parameter is useful for adding business data read from auth tokens to the request.

This plugin can be used at the route level as in the above example or at the hook level using the preHandler hook:

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

…

js
{
  defaultRelation: 'and'
}
  • defaultRelation (Default: or): The default relation between the functions. It can be either or or and.

Acknowledgments

Past sponsors:

  • LetzDoIt

License

Licensed under MIT.

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

JavaScriptauthenticationfastifyfastify-pluginstrategy-pattern

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类安全
定价开源

> 相关工具

O
OWASP ZAP
开源 Web 应用安全扫描器
O
owasp-wstg-tracker
Simple web app to track OWASP WSTG security testing progress
H
homebridge-mi-gateway-security
XiaoMi Gateway Security plugin for HomeBridge.