Integrate @fastify/bearer-auth with @fastify/auth
mainTo use @fastify/bearer-auth as one of several authentication schemes within @fastify/auth, follow these steps:
- Register
@fastify/bearer-authwith{ addHook: false }. This prevents the plugin from immediately replying with a 401, allowing@fastify/authto proceed to the next scheme if authentication fails. - Use
fastify.verifyBearerAuthinside thepreHandlerarray of your route configuration. - (Optional) Set
verifyErrorLogLevel: 'debug'to suppress error logs during the multi-auth flow.
If verifyBearerAuth is the last hook in the @fastify/auth list, @fastify/auth will automatically reply with Unauthorized if it fails.
const fastify = require('fastify')()
const auth = require('@fastify/auth')
const bearerAuthPlugin = require('@fastify/bearer-auth')
const keys = new Set(['a-super-secret-key', 'another-super-secret-key'])
async function server() {
await fastify
.register(auth)
.register(bearerAuthPlugin, { addHook: false, keys, verifyErrorLogLevel: 'debug' })
.decorate('allowAnonymous', function (req, reply, done) {
if (req.headers.authorization) {
return done(Error('not anonymous'))
}
return done()
})
fastify.route({
method: 'GET',
url: '/multiauth',
preHandler: fastify.auth([
fastify.allowAnonymous,
fastify.verifyBearerAuth
]),
handler: function (_, reply) {
reply.send({ hello: 'world' })
}
})
await fastify.listen({port: 8000})
}
server()