Fastify:省略一些使用基本身份验证的 API

Fastify: Ommit some APIs from using basic authentication

目前,我有两个 API:/auth/no-auth

我希望只有其中之一使用基本身份验证。

我在 node 中的 fastify 之上使用 fastify-basic-auth 插件。

/auth 应该需要身份验证。

/no-auth 不应要求身份验证。

目前,我的代码设置方式,BOTH 都需要身份验证。

fastify.register(require('fastify-basic-auth'), { validate, authenticate })

function validate (username, password, req, reply, done) {
  if (isValidAuthentication(username, password)) {
    done()
  } else {
    done(new Error('Whoops!'))
  }
}

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

  // This one should require basic auth
  fastify.get('/auth', (req, reply) => {
    reply.send({ hello: 'world' })
  })
})

// This one should not require basic-auth.
fastify.get('/no-auth', (req, reply) => {
  reply.send({ hello: 'world' })
})

要存档它,您需要创建一个新的封装上下文调用 register:


fastify.register(async function plugin (instance, opts) {
  await instance.register(require('fastify-basic-auth'), { validate, authenticate })
  instance.addHook('onRequest', instance.basicAuth)

  // This one should require basic auth
  instance.get('/auth', (req, reply) => {
    reply.send({ hello: 'world' })
  })
})

// This one should not require basic-auth.
fastify.get('/not-auth', (req, reply) => {
  reply.send({ hello: 'world' })
})

function validate (username, password, req, reply, done) {
  if (isValidAuthentication(username, password)) {
    done()
  } else {
    done(new Error('Whoops!'))
  }
}