Giter Club home page Giter Club logo

fastify-basic-auth's Introduction

@fastify/basic-auth

CI NPM version js-standard-style

A simple basic auth plugin for Fastify.

Install

npm i @fastify/basic-auth

Usage

This plugin decorates the fastify instance with a basicAuth function, which you can use inside any hook before your route handler, or with @fastify/auth.

const fastify = require('fastify')()
const authenticate = {realm: 'Westeros'}
fastify.register(require('@fastify/basic-auth'), { validate, authenticate })
// `this` inside validate is `fastify`
function validate (username, password, req, reply, done) {
  if (username === 'Tyrion' && password === 'wine') {
    done()
  } else {
    done(new Error('Winter is coming'))
  }
}

fastify.after(() => {
  fastify.addHook('onRequest', fastify.basicAuth)

  fastify.get('/', (req, reply) => {
    reply.send({ hello: 'world' })
  })
})

Promises and async/await are supported as well!

const fastify = require('fastify')()
const authenticate = {realm: 'Westeros'}
fastify.register(require('@fastify/basic-auth'), { validate, authenticate })
async function validate (username, password, req, reply) {
  if (username !== 'Tyrion' || password !== 'wine') {
    return new Error('Winter is coming')
  }
}

Use with onRequest:

const fastify = require('fastify')()
const authenticate = {realm: 'Westeros'}
fastify.register(require('@fastify/basic-auth'), { validate, authenticate })
async function validate (username, password, req, reply) {
  if (username !== 'Tyrion' || password !== 'wine') {
    return new Error('Winter is coming')
  }
}

fastify.after(() => {
  fastify.route({
    method: 'GET',
    url: '/',
    onRequest: fastify.basicAuth,
    handler: async (req, reply) => {
      return { hello: 'world' }
    }
  })
})

Use with @fastify/auth:

const fastify = require('fastify')()
const authenticate = {realm: 'Westeros'}
fastify.register(require('@fastify/auth'))
fastify.register(require('@fastify/basic-auth'), { validate, authenticate })
async function validate (username, password, req, reply) {
  if (username !== 'Tyrion' || password !== 'wine') {
    return new Error('Winter is coming')
  }
}

fastify.after(() => {
  // use preHandler to authenticate all the routes
  fastify.addHook('preHandler', fastify.auth([fastify.basicAuth]))

  fastify.route({
    method: 'GET',
    url: '/',
    // use onRequest to authenticate just this one
    onRequest: fastify.auth([fastify.basicAuth]),
    handler: async (req, reply) => {
      return { hello: 'world' }
    }
  })
})

Custom error handler

On failed authentication, @fastify/basic-auth will call the Fastify generic error handler with an error. @fastify/basic-auth sets the err.statusCode property to 401.

In order to properly 401Β errors:

fastify.setErrorHandler(function (err, req, reply) {
  if (err.statusCode === 401) {
    // this was unauthorized! Display the correct page/message.
    reply.code(401).send({ was: 'unauthorized' })
    return
  }
  reply.send(err)
})

Options

utf8 (optional, default: true)

User-ids or passwords containing characters outside the US-ASCII character set will cause interoperability issues, unless both communication partners agree on what character encoding scheme is to be used. If utf8 is set to true the server will send the 'charset' parameter to indicate a preference of "UTF-8", increasing the probability that clients will switch to that encoding.

strictCredentials (optional, default: true)

If strictCredentials is set to false the authorization header can contain additional whitespaces at the beginning, in the midde and at the end of the authorization header. This is a fallback option to ensure the same behaviour as @fastify/basic-auth version <=5.x.

validate (required)

The validate function is called on each request made, and is passed the username, password, req and reply parameters in that order. An optional fifth parameter, done may be used to signify a valid request when called with no arguments, or an invalid request when called with an Error object. Alternatively, the validate function may return a promise, resolving for valid requests and rejecting for invalid. This can also be achieved using an async/await function, and throwing for invalid requests.

See code above for examples.

authenticate <Boolean|Object> (optional, default: false)

When supplied, the authenticate option will cause the WWW-Authenticate header to be added. It may also be used to set the realm value.

This can be useful in situations where we want to trigger client-side authentication interfaces - for instance the browser authentication dialog.

As a boolean setting authenticate to true will set a header like so: WWW-Authenticate: Basic. When false, no header is added. This is the default.

fastify.register(require('@fastify/basic-auth'), {
  validate,
  authenticate: true // WWW-Authenticate: Basic
})

fastify.register(require('@fastify/basic-auth'), {
  validate,
  authenticate: false // no authenticate header, same as omitting authenticate option
})

When supplied as an object the authenticate option may have a realm key.

If the realm key is supplied, it will be appended to the header value:

fastify.register(require('@fastify/basic-auth'), {
  validate,
  authenticate: {realm: 'example'} // WWW-Authenticate: Basic realm="example"
})

The realm key could also be a function:

fastify.register(require('@fastify/basic-auth'), {
  validate,
  authenticate: {
    realm(req) {
      return 'example' // WWW-Authenticate: Basic realm="example"
    }
  }
})

header String (optional)

When supplied, the header option is the name of the header to get credentials from for validation.

fastify.register(require('@fastify/basic-auth'), {
  validate,
  header: 'x-forwarded-authorization'
})

License

Licensed under MIT.

fastify-basic-auth's People

Contributors

cemremengu avatar climba03003 avatar crutch12 avatar delvedor avatar dependabot-preview[bot] avatar dependabot[bot] avatar eomm avatar fdawgs avatar hschwalm avatar jsumners avatar matthyk avatar mattyod avatar mcollina avatar rafaelgss avatar ricardo-devis-agullo avatar salmanm avatar uzlopak avatar vjau avatar zekth avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fastify-basic-auth's Issues

Add TypeScript definitions

πŸš€ Feature Proposal

Add an index.d.ts with Typescript type definitions.

Motivation

To use it on Typescript projects.

I can do a PR for this if you are ok with it.

UnauthorizedError: Missing or bad formatted authorization header

I'm using fastify-swagger to generate my Swagger API documentation. Now I want protect this documentation using this plugin but I'm always getting the following error:

UnauthorizedError: Missing or bad formatted authorization header

I've added the fastify-basic-auth plugin as described:

  const fastify = require('fastify')({
    logger: false
  })

  fastify.register(require('fastify-basic-auth'), {
    validate: async function (...args) {
      console.log(args)
    },
    authenticate: true // WWW-Authenticate: Basic
  })

  fastify.after(() => {
    fastify.addHook('preHandler', fastify.basicAuth)
  })

  await fastify.listen(8888)

According to the documentation, setting the "authenticate" option to true:

This can be useful in situations where we want to trigger client-side authentication interfaces - for instance the browser authentication dialog.

As a boolean setting authenticate to true will set a header like so: WWW-Authenticate: Basic. When false, no header is added. This is the default.

But I'm get no dialog where I can enter my credentials. Instead I'm getting the "UnauthorizedError". What I'm doing wrong here?

Allow custom decorate name

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

πŸš€ Feature Proposal

I have a use case where I want to have 2 different basic auth functions for different routes. It would be nice if I could register the basic-auth plugin twice and customize the decorate name:

fastify.decorate('basicAuth', basicAuth)

Motivation

I want to support different basic auth logic on different routes, and would like to register 2 different validate functions on different decorated names off of fastify.

Example

fastify.register(require('@fastify/basic-auth'), { validate, authenticate, namespace: 'otherBasicAuth' })

fastify.after(() => {
  fastify.addHook('onRequest', otherBasicAuth)

  fastify.get('/', (req, reply) => {
    reply.send({ hello: 'world' })
  })
})

Something like this. Happy to contribute this.

ChainAlert: npm package release (2.3.0) has no matching tag in this repo

Dear fastify-basic-auth maintainers,
Thank you for your contribution to the open-source community.

This issue was automatically created to inform you a new version (2.3.0) of fastify-basic-auth was published without a matching tag in this repo.

As part of our efforts to fight software supply chain attacks, we would like to verify this release is known and intended, and not a result of an unauthorized activity.

If you find this behavior legitimate, kindly close and ignore this issue. Read more

badge

Add example of how to add credentials to request to README

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

πŸš€ Feature Proposal

Add a simple example of how to add credentials to a request, to make it easier for beginners to use the plugin.

It's my first Issue so im sorry if i did something wrong

Motivation

it is unclear, where this plugin gets its the username and password from, if one is not familiar with how authorisation works

Example

How to add Credentials to request

The basic-auth plugin retrieves the credentials from the Authorization header.

        const credentials: string = Buffer.from("username:password").toString('base64')
       request.header("Authorisazion", "Basic " + credentials)

Set custom auth header

πŸš€ Feature Proposal

Add the ability to set a custom authorization header.

If a header property exists in options then use basic-auths auth.parse() method rather than auth().

Motivation

Some of our services sit behind an API Gateway that transfers incoming authorization headers onto a custom x-forwarded-authorization header. Unfortunately that API Gateway does not provide basic authentication checks 🀷 , so authentication still needs to be done within the service. (there are other benefits to the Gateway in case you are wondering πŸ˜„ ).

Example

fastify.register(basicAuth, { validate, authenticate, header: 'x-forwarded-authorization` }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.