@fastify/bearer-auth

repository·main·Indexed 41 days ago

https://github.com/fastify/fastify-bearer-auth

A Bearer authentication plugin for Fastify (version 10.1.3) that provides a request hook to protect routes using a set of valid keys or a custom validation function. It supports RFC 6749 and RFC 6750 compliance, custom error responses, and integration with @fastify/auth.

Tokens
2.8K
Snippets
8
Records
12
Agent score
50%

What's inside fastify-bearer-auth

  1. Integrate @fastify/bearer-auth with @fastify/auth

    main

    To use @fastify/bearer-auth as one of several authentication schemes within @fastify/auth, follow these steps:

    1. Register @fastify/bearer-auth with { addHook: false }. This prevents the plugin from immediately replying with a 401, allowing @fastify/auth to proceed to the next scheme if authentication fails.
    2. Use fastify.verifyBearerAuth inside the preHandler array of your route configuration.
    3. (Optional) Set verifyErrorLogLevel: 'debug' to suppress error logs during the multi-auth flow.

    If verifyBearerAuth is the last hook in the @fastify/auth list, @fastify/auth will automatically reply with Unauthorized if it fails.

    const fastify = require('fastify')()
    const auth = require('@fastify/auth')
    const bearerAuthPlugin = require('@fastify/bearer-auth')
    const keys = new Set(['a-super-secret-key', 'another-super-secret-key'])
    
    async function server() {
    
      await fastify
        .register(auth)
        .register(bearerAuthPlugin, { addHook: false, keys, verifyErrorLogLevel: 'debug' })
        .decorate('allowAnonymous', function (req, reply, done) {
          if (req.headers.authorization) {
            return done(Error('not anonymous'))
          }
          return done()
        })
    
      fastify.route({
        method: 'GET',
        url: '/multiauth',
        preHandler: fastify.auth([
          fastify.allowAnonymous,
          fastify.verifyBearerAuth
        ]),
        handler: function (_, reply) {
          reply.send({ hello: 'world' })
        }
      })
    
      await fastify.listen({port: 8000})
    }
    
    server()
  2. Use a custom authentication function instead of static keys

    main

    Instead of providing a static list of keys, you can provide an auth function. This is useful for looking up tokens in a database or performing more complex validation logic.

    The auth function is called with (key, request). It can be a synchronous function or an asynchronous function (returning a Promise). It must return a truthy value to authorize the request, or false to deny it. If the function throws an error or returns a rejected promise, the plugin will respond with a 500 Internal Server Error.

    Note: When auth is provided, the keys option is ignored.

    const options = {
      auth: async (key, request) => {
        const user = await database.findUserByToken(key)
        return !!user // Return true if user exists, false otherwise
      }
    }
  3. Understand specCompliance: rfc6749 vs rfc6750

    main

    The specCompliance option controls how the Authorization header prefix is validated:

    • rfc6750 (Default): The prefix is case-sensitive and must match the bearerType exactly (e.g., if bearerType is 'Bearer', the header must start with 'Bearer ').
    • rfc6749: The prefix is case-insensitive (e.g., if bearerType is 'Bearer', the header can start with 'bearer ' or 'Bearer ').
  4. Use @fastify/bearer-auth without automatic hooks

    main

    If you set addHook: false in the plugin options, the plugin will not automatically intercept requests. Instead, it decorates the Fastify instance, allowing you to manually trigger authentication logic.

    It provides two decorations:

    1. fastify.verifyBearerAuthFactory: A factory function to create custom verification functions.
    2. fastify.verifyBearerAuth: A pre-configured verification function based on the plugin's initial options.
    fastify.register(require('@fastify/bearer-auth'), {
      addHook: false
    })
    
    // Use the decorated verification function in a specific route
    fastify.get('/protected', { preHandler: fastify.verifyBearerAuth }, async (request, reply) => {
      return { hello: 'world' }
    })
  5. Configure @fastify/bearer-auth options

    main

    When registering the plugin, you can provide a configuration object. The default configuration is:

    {
      keys: new Set(),
      contentType: undefined,
      bearerType: 'Bearer',
      specCompliance: 'rfc6750',
      errorResponse: (err) => {
        return {error: err.message}
      },
      auth: undefined,
      addHook: true
    }

    Option Reference

    • keys (required): A Set or array of valid string keys.
    • auth (optional): A function (key, req) => boolean | Promise<boolean> to test if a key is valid. If provided, keys is ignored.
    • errorResponse (optional): A function (err) => body that must synchronously return the content body to be sent to the client on authentication failure.
    • contentType (optional): The content type to use if the response is not application/json.
    • bearerType (optional): String specifying the Bearer prefix (defaults to 'Bearer').
    • specCompliance (optional): Determines token type matching. Accepts 'rfc6749' (case-insensitive) or 'rfc6750' (exact match, default).
    • addHook (optional): Controls how the plugin is applied:
      • true: Registers an onRequest hook (default).
      • 'onRequest': Registers an onRequest hook.
      • 'preParsing': Registers a preParsing hook.
      • false: Does not register a hook, but exposes fastify.verifyBearerAuth and fastify.verifyBearerAuthFactory decorators.
    • verifyErrorLogLevel (optional): A valid Fastify log level for verification errors (defaults to 'error').
  6. Register the @fastify/bearer-auth plugin

    main

    Register @fastify/bearer-auth with your Fastify instance to handle Bearer token authentication. By default, the plugin adds an onRequest hook to your application that validates the Authorization: Bearer <token> header.

    To use the plugin, call fastify.register(require('@fastify/bearer-auth'), options).

    const fastify = require('fastify')()
    
    fastify.register(require('@fastify/bearer-auth'), {
      // options
    })
  7. Basic usage of @fastify/bearer-auth

    main

    To use the plugin, register it with a keys option containing a Set or array of valid strings. By default, it registers an onRequest hook that protects all routes within its scope.

    'use strict'
    
    const fastify = require('fastify')()
    const bearerAuthPlugin = require('@fastify/bearer-auth')
    const keys = new Set(['a-super-secret-key', 'another-super-secret-key'])
    
    fastify.register(bearerAuthPlugin, {keys})
    fastify.get('/foo', (req, reply) => {
      reply.send({authenticated: true})
    })
    
    fastify.listen({port: 8000}, (err) => {
      if (err) {
        fastify.log.error(err.message)
        process.exit(1)
      }
      fastify.log.info('http://127.0.0.1:8000/foo')
    })
  8. Configure the @fastify/bearer-auth plugin options

    main

    When registering the plugin, you can provide the following configuration options:

    • addHook: Determines which Fastify hook is used for authentication.
      • Supported values: 'onRequest', 'preParsing', or false.
      • If set to true or omitted, it defaults to 'onRequest'.
      • If set to false, the plugin will not add a hook but will instead decorate the Fastify instance with authentication functions.
      • Note: Using 'preParsing' is useful for protecting against DoS attacks.
    • verifyErrorLogLevel: Specifies which method on fastify.log should be used to log verification errors.
      • Defaults to 'error'.
      • Must be a valid function name existing on the fastify.log object (e.g., 'error', 'warn').
      • If fastify.log does not support the specified level, or if the log object is invalid, the level is set to null.
  9. Troubleshoot @fastify/bearer-auth authentication errors

    main

    During request processing, the plugin throws specific errors if the Authorization header is missing or malformed. These errors are associated with HTTP status code 401.

    // Error codes for request authentication:
    FST_BEARER_AUTH_MISSING_AUTHORIZATION_HEADER: 'missing authorization header' (HTTP 401)
    FST_BEARER_AUTH_INVALID_AUTHORIZATION_HEADER: 'invalid authorization header' (HTTP 401)
  10. Troubleshoot @fastify/bearer-auth configuration errors

    main

    When registering the @fastify/bearer-auth plugin, you may encounter specific error codes if the provided options do not match the required schema. These errors are thrown during the plugin registration phase.

    // Error codes for configuration validation:
    FST_BEARER_AUTH_INVALID_KEYS_OPTION_TYPE: 'options.keys has to be an Array or a Set'
    FST_BEARER_AUTH_INVALID_HOOK: 'options.addHook must be either "onRequest" or "preParsing"'
    FST_BEARER_AUTH_INVALID_LOG_LEVEL: 'fastify.log does not have level 	ext{'%s'}'
    FST_BEARER_AUTH_KEYS_OPTION_INVALID_KEY_TYPE: 'options.keys has to contain only string entries'
    FST_BEARER_AUTH_INVALID_SPEC: 'options.specCompliance has to be set to \'rfc6750\' or \'rfc6749\''