Share your code. npm Orgs help your team discover, share, and reuse code. Create a free org »

fastify-auth

0.2.0 • Public • Published

fastify-auth

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.

install

npm i fastify-auth

Downloadsweekly downloads

42

version

0.2.0

license

MIT

repository

githubgithub

last publish

collaborators

  • avatar
  • avatar