fastify / fastify/help

How to know which strategy was used by fastify-auth?

Open
#1,083 1 comment 0 reactions 0 assignees View on GitHub
help wanted
Dominant language
No language data
Stars
68
Forks
8
Avg merge
11h 2m
Merged PRs (30d)
2

Description

## 💬 Question here

I use fastify-bearer-auth with fastify-auth to authenticate requests. I have a few endpoints where the bearer auth is optional. This pretty much follows this example perfectly: https://github.com/fastify/fastify-bearer-auth?tab=readme-ov-file#integration-with-fastifyauth

However, my endpoints should respond differently to the request depending on which of the two strategies was used.

So, in my request handler, how can I know if fastify-auth authenticated the request with bearer auth or as anonymous?

```js
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 (req, reply) {
if (AUTH WAS BEARER) { // <--- How to make this check?
reply.send({ auth: 'bearer' })
} else {
reply.send({ auth: 'anonymous'});
}
}
})
````

## Your Environment

- *node version*: 23
- *fastify version*: >=5.2.0
- *os*: Linux

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.