Skip to content

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

@fusionfoxy

Description

@fusionfoxy

💬 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedExtra attention is needed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions