Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
fusionfoxy opened this issue Feb 21, 2025 · 0 comments
Open

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

fusionfoxy opened this issue Feb 21, 2025 · 0 comments
Labels
help wanted Extra attention is needed

Comments

@fusionfoxy
Copy link

💬 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?

  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
@fusionfoxy fusionfoxy added the help wanted Extra attention is needed label Feb 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

1 participant