Fastify: Ommit some APIs from using basic authentication



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' })
})

Answer

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!'))
  }
}



Source: stackoverflow