Fastify:禁止一些API使用基本身份验证



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

我希望ONLY其中一个使用基本身份验证。

我在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!'))
}
}

最新更新