0

Currently, I have two APIs: /auth and /no-auth.

I would like ONLY one of them to use basic-auth.

I am using fastify-basic-auth plugin on top of fastify in node.

/auth should require authentication.

/no-auth should NOT require authentication.

Currently, the way my code is set up, BOTH are requiring authentication.

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' })
})
Eduardo Morales
  • 764
  • 7
  • 29

1 Answers1

2

To archive it you need to create a new encapsulated context calling 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!'))
  }
}

Manuel Spigolon
  • 11,003
  • 5
  • 50
  • 73