Run multiple auth functions in Fastify
Clone or download
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.gitignore Updated .gitignore Jul 8, 2017
.travis.yml updated dependecies (#18) Jul 10, 2018
LICENSE Initial commit Jul 8, 2017
README.md docs(readme): add Greenkeeper badge Mar 4, 2018
example.js Updated example.js Sep 17, 2017
fastify-auth.js Better implementation Jul 19, 2017
package.json chore(package): update standard to version 12.0.1 (#24) Oct 16, 2018
test.js Updated dependencies Feb 12, 2018

README.md

fastify-auth

Greenkeeper badge

js-standard-style Build Status

This module does not provide an authentication strategy, but it provides a very fast utility to handle authentication (also multiple strategies) in your routes, without adding overhead.
Check out the complete example here.

Install

npm i fastify-auth --save

Usage

As said above, fastify-auth does not provide an authentication strategy, so you must provide it (or them) by yourself, with a decorator or another plugin. In the following example you will find a very simple implementation that should help you understand how use this module.

fastify
  .decorate('verifyJWTandLevel', function (request, reply, done) {
    // your validation logic
    done() // pass an error if the authentication fails
  })
  .decorate('verifyUserAndPassword', function (request, reply, done) {
    // your validation logic
    done() // pass an error if the authentication fails
  })
  .register(require('fastify-auth'))
  .after(() => {
    fastify.route({
      method: 'POST',
      url: '/auth-multiple',
      beforeHandler: fastify.auth([
        fastify.verifyJWTandLevel,
        fastify.verifyUserAndPassword
      ]),
      handler: (req, reply) => {
        req.log.info('Auth route')
        reply.send({ hello: 'world' })
      }
    })
  })

Keep in mind that route definition should either be done as a plugin or within .after() callback. For complete example implementation see example.js.

fastify-auth will run all your authentication methods if at least one succeed it will continue your request, otherwise it will return an error to the client. It will automatically stop as soon as a authentication succeed.

You can use this plugin on route level, as in the above example or on hook level, by using the preHandler hook:

fastify.addHook('preHandler', fastify.auth([
  fastify.verifyJWTandLevel,
  fastify.verifyUserAndPassword
]))

fastify.route({
  method: 'POST',
  url: '/auth-multiple',
  handler: (req, reply) => {
    req.log.info('Auth route')
    reply.send({ hello: 'world' })
  }
})

The difference between the two approaches is that if you use the beforeHandler the authentication will run just for the selected route, while if you use the preHandler hook the authentication will run for all the routes declared inside the current plugin (and its sons).

Acknowledgements

This project is kindly sponsored by:

License

Licensed under MIT.