### Basic Bearer Token Authentication Setup Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/README.md Set up basic Bearer token authentication by registering the plugin with a set of valid keys. This example also shows example requests and responses for valid and invalid tokens. ```javascript const fastify = require('fastify')() const bearerAuth = require('@fastify/bearer-auth') fastify.register(bearerAuth, { keys: new Set(['valid-token-1', 'valid-token-2']) }) fastify.get('/secure', (request, reply) => { reply.send({ message: 'Authenticated' }) }) fastify.listen({ port: 3000 }) ``` -------------------------------- ### Basic Usage Example Source: https://github.com/fastify/fastify-bearer-auth/blob/main/Readme.md A simple example demonstrating how to register and use the @fastify/bearer-auth plugin with a set of predefined keys. ```APIDOC ## Example ```js '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') }) ``` ``` -------------------------------- ### Directory Structure Example Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/INDEX.md Illustrates the directory structure of the project, showing the location of key documentation files and API reference modules. ```bash output/ ├── README.md (Overview & navigation) ├── INDEX.md (This file) ├── types.md (Type definitions) ├── configuration.md (Option reference) ├── errors.md (Error catalog) └── api-reference/ ├── fastify-bearer-auth.md (Main plugin) ├── verify-bearer-auth-factory.md (Hook factory) ├── authenticate.md (Token validation) └── compare.md (Timing-safe compare) ``` -------------------------------- ### Installation Source: https://github.com/fastify/fastify-bearer-auth/blob/main/Readme.md Install the @fastify/bearer-auth plugin using npm. ```APIDOC ## Install ``` npm i @fastify/bearer-auth ``` ``` -------------------------------- ### Install @fastify/bearer-auth Source: https://github.com/fastify/fastify-bearer-auth/blob/main/Readme.md Use npm to install the @fastify/bearer-auth package. ```bash npm i @fastify/bearer-auth ``` -------------------------------- ### Complete Fastify Bearer Auth Configuration Example Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/configuration.md This example demonstrates a comprehensive configuration of the Fastify Bearer Auth plugin, including required keys, optional authentication logic, custom error responses, and various other settings. ```javascript const fastify = require('fastify')() const bearerAuth = require('@fastify/bearer-auth') fastify.register(bearerAuth, { // Required keys: new Set(['token-1', 'token-2']), // Optional: Authentication auth: async (token, request) => { const user = await db.users.findByToken(token) return user !== null }, // Optional: Error Handling errorResponse: (err) => ({ code: 'UNAUTHORIZED', message: err.message, timestamp: new Date().toISOString() }), contentType: 'application/json', // Optional: Bearer Configuration bearerType: 'Bearer', specCompliance: 'rfc6750', // Optional: Hook Configuration addHook: 'onRequest', verifyErrorLogLevel: 'error' }) ``` -------------------------------- ### Basic Bearer Authentication Example Source: https://github.com/fastify/fastify-bearer-auth/blob/main/Readme.md Register the bearer-auth plugin with a set of valid keys and define a protected route. This example demonstrates how to set up a basic Bearer authentication flow in Fastify. ```javascript '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') }) ``` -------------------------------- ### Source Code Reference Example Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/INDEX.md Demonstrates how source code references are provided in the documentation, including file path and line numbers for specific code sections. ```text Source: lib/verify-bearer-auth-factory.js:32-150 ``` -------------------------------- ### Integration with @fastify/auth Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/README.md Integrate @fastify/bearer-auth with @fastify/auth to enable multi-strategy authentication. This example shows how to use `fastify.auth` to apply both Bearer and Basic authentication. ```javascript const auth = require('@fastify/auth') const bearerAuth = require('@fastify/bearer-auth') fastify.register(auth) fastify.register(bearerAuth, { keys: new Set(['token']), addHook: false }) fastify.route({ method: 'GET', url: '/api', preHandler: fastify.auth([ fastify.verifyBearerAuth, fastify.basicAuth // Try Bearer first, then Basic ]), handler: (request, reply) => { reply.send({ authenticated: true }) } }) ``` -------------------------------- ### Direct Key Validation Example Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/api-reference/authenticate.md Demonstrates how to use the `authenticate` function to directly validate a given key string against an array of valid keys. This is useful for simple, standalone token checks. ```javascript const authenticate = require('@fastify/bearer-auth/lib/authenticate') const validKeys = [ Buffer.from('secret-key-1'), Buffer.from('secret-key-2'), Buffer.from('secret-key-3') ] // Valid key const result = authenticate(validKeys, 'secret-key-1') console.log(result) // true // Invalid key const result = authenticate(validKeys, 'wrong-key') console.log(result) // false ``` -------------------------------- ### Bearer Token Header Format Example Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/README.md Illustrates the required format for the Authorization header, which must include a bearer type followed by the token. ```text Authorization: Bearer my-secret-token ``` -------------------------------- ### Integrate Bearer Auth with Fastify Auth Source: https://github.com/fastify/fastify-bearer-auth/blob/main/Readme.md Use this example to register both @fastify/auth and @fastify/bearer-auth plugins. Configure bearer-auth with specific keys and error logging. Decorate Fastify with an `allowAnonymous` function to check for the absence of an authorization header. Define a route that uses `fastify.auth` to apply multiple pre-handlers, including `allowAnonymous` and `verifyBearerAuth`. ```javascript 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() ``` -------------------------------- ### Configure Bearer Auth with Duplicate Keys Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/configuration.md When providing keys as an array, duplicates are automatically removed. This example shows how duplicate tokens are handled. ```javascript fastify.register(bearerAuth, { keys: ['token', 'token', 'other'] // Results in ['token', 'other'] }) ``` -------------------------------- ### Basic Fastify Bearer Auth with Predefined Keys Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/api-reference/fastify-bearer-auth.md Illustrates the basic usage of the Fastify Bearer Auth plugin by registering it with a predefined set of secret tokens. This setup automatically handles token validation via hooks. ```javascript const fastify = require('fastify')() const bearerAuth = require('@fastify/bearer-auth') fastify.register(bearerAuth, { keys: new Set(['secret-token-1', 'secret-token-2']) }) fastify.get('/secure', (request, reply) => { reply.send({ message: 'Access granted' }) }) fastify.listen({ port: 3000 }) ``` ```http GET /secure HTTP/1.1 Authorization: Bearer secret-token-1 ``` -------------------------------- ### Custom Auth Hook Example Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/api-reference/authenticate.md Shows how to integrate the `authenticate` function into a Fastify custom authentication hook (`onRequest`). This allows for centralized token validation before request processing. ```javascript const authenticate = require('@fastify/bearer-auth/lib/authenticate') const fastify = require('fastify')() const authorizedKeys = [ Buffer.from('api-key-alpha'), Buffer.from('api-key-beta') ] fastify.addHook('onRequest', (request, reply, done) => { const authHeader = request.headers.authorization if (!authHeader || !authHeader.startsWith('Bearer ')) { reply.code(401).send({ error: 'Missing or invalid auth header' }) return } const token = authHeader.slice(7) // Remove 'Bearer ' prefix if (authenticate(authorizedKeys, token)) { done() } else { reply.code(401).send({ error: 'Invalid token' }) } }) ``` -------------------------------- ### Registering the Bearer Auth Hook Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/types.md Example of how to add the bearer auth hook to Fastify using the verifyBearerAuthFactory. Ensure the factory is imported correctly. ```typescript import { verifyBearerAuthFactory } from '@fastify/bearer-auth' const hook = verifyBearerAuthFactory({ keys: new Set(['token1', 'token2']) }) fastify.addHook('onRequest', hook) ``` -------------------------------- ### Fastify Bearer Auth Plugin Import (ESM) Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/types.md Example of importing the Fastify Bearer Auth plugin and its associated types using ECMAScript Modules (ESM). ```typescript import fastifyBearerAuth, { FastifyBearerAuthOptions, verifyBearerAuth, verifyBearerAuthFactory } from '@fastify/bearer-auth' ``` -------------------------------- ### Fastify Bearer Auth Plugin Import (CommonJS) Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/types.md Example of importing the Fastify Bearer Auth plugin using CommonJS module system. Type definitions are available in the 'types/index.d.ts' file. ```javascript const fastifyBearerAuth = require('@fastify/bearer-auth') // Type definitions available in types/index.d.ts ``` -------------------------------- ### Correcting Invalid Authorization Header Formats Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/errors.md Shows examples of correctly formatting the Authorization header for different scenarios, including default Bearer type, custom types, and case-insensitive compliance. ```javascript // ✅ Correct format with default bearer type fetch('/protected-route', { headers: { 'Authorization': 'Bearer your-valid-token' } }) // ✅ With custom bearer type (if configured) fetch('/protected-route', { headers: { 'Authorization': 'ApiKey your-api-key' } }) // ✅ Case-insensitive with RFC6749 compliance fetch('/protected-route', { headers: { 'Authorization': 'bearer your-token' // lowercase works with rfc6749 } }) ``` -------------------------------- ### Custom Asynchronous Authentication Function (Database) Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/configuration.md Use an asynchronous function for token validation, such as querying a database. This example demonstrates fetching user data by API key and returning true if a user is found. ```javascript fastify.register(bearerAuth, { auth: async (token, request) => { try { const user = await database.users.findByApiKey(token) if (user) { // Attach user to request for use in handlers request.user = user return true } return false } catch (err) { request.log.error('Token validation error: %s', err.message) return false // Return false on error, don't throw } } }) ``` -------------------------------- ### Using verifyBearerAuthFactory Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/types.md Demonstrates how to use the `verifyBearerAuthFactory` to create custom hooks with different options than the plugin's main hook. ```APIDOC ## Using verifyBearerAuthFactory ### Description Creates a custom bearer authentication hook with specific options, allowing for more granular control over authentication. ### Method `fastify.verifyBearerAuthFactory()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (`FastifyBearerAuthOptions`) - Options to configure the custom hook. - **keys** (`Set`) - A set of valid bearer tokens. - **bearerType** (`string`, optional) - The expected bearer type (default: 'Bearer'). ### Usage Example ```typescript const customHook = fastify.verifyBearerAuthFactory({ keys: new Set(['custom-token']), bearerType: 'CustomAuth' }) // Use customHook in a route's preHandler fastify.route({ method: 'GET', url: '/custom-protected', preHandler: customHook, handler: async (request, reply) => { reply.send({ custom_secure: true }) } }) ``` ``` -------------------------------- ### Fastify Instance with verifyBearerAuthFactory Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/api-reference/fastify-bearer-auth.md Shows how to use the `verifyBearerAuthFactory` to create custom verification hooks with specific options, such as custom keys and bearer types. This factory is always available on the Fastify instance. ```javascript const customVerify = fastify.verifyBearerAuthFactory({ keys: new Set(['custom-key']), bearerType: 'CustomBearer' }) ``` -------------------------------- ### Fastify Instance with verifyBearerAuth Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/api-reference/fastify-bearer-auth.md Demonstrates how to use the `verifyBearerAuth` function, which is available when `addHook` is set to `false`. This function must be manually invoked in route handlers or other hooks. ```javascript fastify.route({ method: 'GET', url: '/protected', preHandler: fastify.verifyBearerAuth, handler: (request, reply) => { reply.send({ secure: true }) } }) ``` -------------------------------- ### Plugin Configuration Options Source: https://github.com/fastify/fastify-bearer-auth/blob/main/Readme.md Details on the configuration options available when registering the @fastify/bearer-auth plugin. ```APIDOC ## API *@fastify/bearer-auth* exports a standard [Fastify plugin](https://github.com/fastify/fastify-plugin). This allows registering the plugin within scoped paths, so some paths can be protected by the plugin while others are not. See the [Fastify](https://fastify.dev/docs/latest) documentation and examples for more details. When registering the plugin a configuration object must be specified: * `keys`: A `Set` or array with valid keys of type `string` (required) * `function errorResponse (err) {}`: Method must synchronously return the content body to be sent to the client (optional) * `contentType`: If the content to be sent is anything other than `application/json`, then the `contentType` property must be set (optional) * `bearerType`: String specifying the Bearer string (optional) * `specCompliance`: Plugin spec compliance. Accepts either [`rfc6749`](https://datatracker.ietf.org/doc/html/rfc6749) or [`rfc6750`](https://datatracker.ietfa.org/doc/html/rfc6750). Defaults to `rfc6750`. * `rfc6749` is about the generic OAuth2.0 protocol, which allows the token type to be case-insensitive * `rfc6750` is about the Bearer Token Usage, which forces the token type to be an exact match * `function auth (key, req) {}` : This function tests if `key` is a valid token. It must return `true` if accepted or `false` if rejected. The function may also return a promise that resolves to one of these values. If the function returns or resolves to any other value, rejects, or throws, an HTTP status of `500` will be sent. `req` is the Fastify request object. If `auth` is a function, `keys` will be ignored. If `auth` is not a function or `undefined`, `keys` will be used * `addHook`: Accepts a boolean, `'onRequest'`, or `'preParsing'` (optional, defaults to `'onRequest'`): * `true` registers an `onRequest` hook * `'onRequest'` and `'preParsing'` registers their respective hooks * `false` will not register a hook, and the `fastify.verifyBearerAuth` and `fastify.verifyBearerAuthFactory` decorators will be exposed * `verifyErrorLogLevel`: An optional string specifying the log level for verification errors. It must be a valid log level supported by Fastify, or an exception will be thrown when registering the plugin. By default, this option is set to `error` The default configuration object is: ```js { keys: new Set(), contentType: undefined, bearerType: 'Bearer', specCompliance: 'rfc6750', errorResponse: (err) => { return {error: err.message} }, auth: undefined, addHook: true } ``` The plugin registers a standard Fastify [onRequest hook][onrequesthook] to inspect the request's headers for an `authorization` header in the format `bearer key`. The `key` is matched against the configured `keys` object using a [constant time algorithm](https://en.wikipedia.org/wiki/Time_complexity#Constant_time) to prevent [timing-attacks](https://snyk.io/blog/node-js-timing-attack-ccc-ctf/). If the `authorization` header is missing, malformed, or the `key` does not validate, a 401 response is sent with a `{error: message}` body, and no further request processing is performed. [onrequesthook]: https://github.com/fastify/fastify/blob/main/docs/Reference/Hooks.md#onrequest ``` -------------------------------- ### Configure Bearer Auth with a Set of Keys Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/configuration.md Use a Set for efficient, constant-time comparison of bearer tokens. This is the preferred method for providing a list of valid tokens. ```javascript fastify.register(bearerAuth, { keys: new Set(['api-key-1', 'api-key-2', 'api-key-3']) }) ``` -------------------------------- ### Using verifyBearerAuth hook Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/types.md This shows how to use the `verifyBearerAuth` hook, which is a bound hook function implementing the specified options, available when `addHook` is false. ```APIDOC ## Using verifyBearerAuth Hook ### Description Applies the bearer token verification as a pre-handler hook for a specific route. ### Method `fastify.route()` with `preHandler` option. ### Endpoint `/protected` (example) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Usage Example ```typescript fastify.route({ method: 'GET', url: '/protected', preHandler: fastify.verifyBearerAuth, // Assumes plugin was registered with addHook: false handler: async (request, reply) => { reply.send({ secure: true }) } }) ``` ``` -------------------------------- ### TypeScript Type Definitions and Usage Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/README.md Demonstrates how to import and use TypeScript types provided by the @fastify/bearer-auth package for options, verification functions, and factories. ```typescript import fastifyBearerAuth, { FastifyBearerAuthOptions, verifyBearerAuth, verifyBearerAuthFactory } from '@fastify/bearer-auth' // Use in type annotations const options: FastifyBearerAuthOptions = { keys: new Set(['token']) } const hook: verifyBearerAuth = fastifyBearerAuth.verifyBearerAuth const factory: verifyBearerAuthFactory = fastifyBearerAuth.verifyBearerAuthFactory ``` -------------------------------- ### Using verifyBearerAuth Decorator for Route Protection Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/README.md Shows how to protect a specific route using the `fastify.verifyBearerAuth` decorator in the `preHandler` hook. This is available when `addHook` is set to `false` during registration. ```javascript fastify.get('/protected', { preHandler: fastify.verifyBearerAuth, handler: (request, reply) => { reply.send({ data: 'secret' }) } }) ``` -------------------------------- ### Compatibility Table Source: https://github.com/fastify/fastify-bearer-auth/blob/main/Readme.md Compatibility matrix between @fastify/bearer-auth plugin versions and Fastify versions. ```APIDOC ### Compatibility | Plugin version | Fastify version | | ---------------|-----------------| | `^10.x` | `^5.x` | | `^8.x` | `^4.x` | | `^5.x` | `^3.x` | | `^4.x` | `^2.x` | | `^1.x` | `^1.x` | Please note that if a Fastify version is out of support, then so are the corresponding versions of this plugin in the table above. See [Fastify's LTS policy](https://github.com/fastify/fastify/blob/main/docs/Reference/LTS.md) for more details. ``` -------------------------------- ### Creating Custom Authentication Hooks Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/types.md Shows how to create a custom authentication hook using the verifyBearerAuthFactory with specific options like custom tokens and bearer types. This is useful for advanced configurations. ```typescript const customHook = fastify.verifyBearerAuthFactory({ keys: new Set(['custom-token']), bearerType: 'CustomAuth' }) ``` -------------------------------- ### Handling Runtime Errors in Custom Auth Function Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/errors.md Illustrates how to correctly implement a custom authentication function to prevent runtime errors. It shows how to handle potential exceptions and ensure a boolean value is always returned. ```javascript // ❌ Wrong: Not catching errors, returning non-boolean fastify.register(bearerAuth, { auth: async (token) => { const user = await db.findUserByToken(token) // Can throw // Missing return statement - returns undefined } }) // ✅ Correct: Error handling, always returns boolean fastify.register(bearerAuth, { auth: async (token) => { try { const user = await db.findUserByToken(token) return user !== null // Always returns boolean } catch (err) { // Log the error, then return false or rethrow fastify.log.error('Auth error: %s', err.message) return false // Return false instead of throwing } } }) // ✅ Or let the plugin handle the error: fastify.register(bearerAuth, { auth: async (token) => { const user = await db.findUserByToken(token) return Boolean(user) // Explicitly convert to boolean } }) ``` -------------------------------- ### Configure Bearer Auth with an Array of Keys Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/configuration.md Alternatively, provide valid bearer tokens as an array of strings. The plugin will automatically deduplicate and convert them for comparison. ```javascript fastify.register(bearerAuth, { keys: ['api-key-1', 'api-key-2', 'api-key-3'] }) ``` -------------------------------- ### Using the verifyBearerAuth Decorator Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/types.md Demonstrates how to use the verifyBearerAuth decorator for route-specific authentication when addHook is set to false. This allows for more granular control over authentication. ```typescript fastify.route({ method: 'GET', url: '/protected', preHandler: fastify.verifyBearerAuth, handler: async (request, reply) => { reply.send({ secure: true }) } }) ``` -------------------------------- ### Load Bearer Tokens from Environment Variables Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/configuration.md Dynamically load valid bearer tokens from an environment variable, splitting a comma-separated string into a Set. ```javascript fastify.register(bearerAuth, { keys: new Set(process.env.VALID_TOKENS.split(',')) }) ``` -------------------------------- ### Configure Bearer Auth with Warning Error Log Level Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/configuration.md This snippet shows how to register the bearerAuth plugin and set `verifyErrorLogLevel` to 'warn', logging authentication failures at the warning level. ```javascript fastify.register(bearerAuth, { keys: new Set(['token']), verifyErrorLogLevel: 'warn' }) // Log output: // WARN: unauthorized: missing authorization header ``` -------------------------------- ### Fixing Missing Authorization Header Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/errors.md Demonstrates the correct way to include the Authorization header in a fetch request. Ensure the header is present and correctly formatted with a Bearer token. ```javascript // ❌ Wrong fetch('/protected-route') // ✅ Correct fetch('/protected-route', { headers: { 'Authorization': 'Bearer your-token-here' } }) ``` -------------------------------- ### Integrate Bearer Auth with @fastify/auth Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/configuration.md Demonstrates integrating the bearerAuth plugin with the @fastify/auth plugin for creating authentication chains. The bearerAuth plugin is configured for manual hook registration. ```javascript const auth = require('@fastify/auth') const bearerAuth = require('@fastify/bearer-auth') fastify.register(auth) fastify.register(bearerAuth, { keys: new Set(['token']), addHook: false // Don't auto-register }) // Use in auth chains fastify.route({ method: 'GET', url: '/multiauth', preHandler: fastify.auth([ fastify.verifyBearerAuth, fastify.anotherAuthMethod ]), handler: (request, reply) => { reply.send({ authenticated: true }) } }) ``` -------------------------------- ### Default Configuration Object Source: https://github.com/fastify/fastify-bearer-auth/blob/main/Readme.md This object shows the default configuration options for the @fastify/bearer-auth plugin, including keys, error handling, content type, bearer type, spec compliance, custom auth function, and hook registration. ```javascript { keys: new Set(), contentType: undefined, bearerType: 'Bearer', specCompliance: 'rfc6750', errorResponse: (err) => { return {error: err.message} }, auth: undefined, addHook: true } ``` -------------------------------- ### Configure Bearer Auth with Debug Error Log Level Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/configuration.md This snippet demonstrates registering the bearerAuth plugin and setting the `verifyErrorLogLevel` option to 'debug' for more verbose logging of authentication failures. ```javascript fastify.register(bearerAuth, { keys: new Set(['token']), verifyErrorLogLevel: 'debug' }) // Log output when auth fails: // DEBUG: unauthorized: invalid authorization header ``` -------------------------------- ### Catching Invalid Configuration Errors Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/errors.md Demonstrates how to catch configuration errors, such as providing an invalid type for the 'keys' option. The error code 'FST_BEARER_AUTH_INVALID_KEYS_OPTION_TYPE' is logged. ```javascript const fastify = require('fastify')() const bearerAuth = require('@fastify/bearer-auth') try { fastify.register(bearerAuth, { keys: 'not-an-array' // Will throw }) } catch (err) { console.error('Config error:', err.code) // FST_BEARER_AUTH_INVALID_KEYS_OPTION_TYPE } ``` -------------------------------- ### Configure Bearer Auth with RFC6750 (Case-Sensitive) Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/configuration.md Sets the plugin to use RFC6750 compliance for bearer type matching, which is case-sensitive. This is the default and recommended mode. ```javascript fastify.register(bearerAuth, { keys: new Set(['token']), specCompliance: 'rfc6750' // Case-sensitive }) // These succeed: // Authorization: Bearer token // These fail with 401: // Authorization: bearer token (lowercase 'b') // Authorization: BEARER token (uppercase 'B') ``` -------------------------------- ### Configure Authorization Scheme Prefix Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/configuration.md Use the `bearerType` option to define the expected prefix in the `Authorization` header. This allows for custom schemes beyond the default 'Bearer'. ```javascript fastify.register(bearerAuth, { keys: new Set(['token']), bearerType: 'Bearer' // Default }) ``` ```javascript fastify.register(bearerAuth, { keys: new Set(['api-key']), bearerType: 'ApiKey' }) ``` ```javascript const fastify = require('fastify')() const bearerAuth = require('@fastify/bearer-auth') // Public routes use standard Bearer fastify.register(bearerAuth, { keys: new Set(['public-key']), bearerType: 'Bearer' }) // Admin routes use different token type (register in a separate scope) fastify.register(async (fastify) => { fastify.register(bearerAuth, { keys: new Set(['admin-key']), bearerType: 'AdminToken' }) }, { prefix: '/admin' }) ``` -------------------------------- ### Fastify Bearer Auth with Custom Authentication Function Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/api-reference/fastify-bearer-auth.md Demonstrates how to configure the Fastify Bearer Auth plugin with a custom asynchronous authentication function. This allows for complex token validation logic, such as checking against a database. ```javascript const fastify = require('fastify')() const bearerAuth = require('@fastify/bearer-auth') fastify.register(bearerAuth, { auth: async (key, request) => { // Validate token against database const user = await db.users.findByToken(key) return user !== null } }) fastify.get('/api/user', (request, reply) => { reply.send({ user: 'data' }) }) ``` -------------------------------- ### Fastify Bearer Auth Manual Integration Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/api-reference/fastify-bearer-auth.md Shows how to use the Fastify Bearer Auth plugin without automatic hooks by setting `addHook: false`. This requires manual integration of the `verifyBearerAuth` function, often in conjunction with the `@fastify/auth` plugin. ```javascript const fastify = require('fastify')() const bearerAuth = require('@fastify/bearer-auth') const auth = require('@fastify/auth') fastify.register(bearerAuth, { keys: new Set(['token']), addHook: false }) fastify.register(auth) fastify.route({ method: 'GET', url: '/multiauth', preHandler: fastify.auth([ fastify.verifyBearerAuth, fastify.allowAnonymous // another auth method ]), handler: (request, reply) => { reply.send({ hello: 'world' }) } }) ``` -------------------------------- ### Handling Async Auth with Error Logging Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/api-reference/verify-bearer-auth-factory.md Integrate asynchronous authentication logic and configure error logging for authentication failures. This allows for complex token validation and provides detailed logs for debugging. ```javascript const verifyBearerAuthFactory = require('@fastify/bearer-auth').verifyBearerAuthFactory const verifyAuth = verifyBearerAuthFactory({ auth: async (token, request) => { try { const user = await externalAuthService.validate(token) if (user) { request.user = user return true } return false } catch (err) { // Errors from auth function result in 500 response throw err } }, verifyErrorLogLevel: 'debug' // Log all auth errors at debug level }) ``` -------------------------------- ### Registering Bearer Auth with Invalid Keys Type Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/errors.md Demonstrates the incorrect and correct ways to register the bearer-auth plugin when the 'keys' option is not an Array or Set. Ensure 'keys' is an Array or Set for proper configuration. ```javascript // ❌ Wrong fastify.register(bearerAuth, { keys: 'my-token' }) // ✅ Correct fastify.register(bearerAuth, { keys: new Set(['my-token']) }) // or fastify.register(bearerAuth, { keys: ['my-token'] }) ``` -------------------------------- ### FastifyBearerAuthOptions Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/types.md Configuration options for the @fastify/bearer-auth plugin and its verification hook. These options allow customization of token validation, error handling, and hook registration. ```APIDOC ## FastifyBearerAuthOptions ### Description Configuration options for the plugin and verification hook. Allows customization of token validation, error handling, and hook registration. ### Fields - **keys** (`Set` | `string[]`) - Required - Array or Set of valid bearer tokens. Ignored if `auth` function is provided. - **auth** (`(key: string, req: FastifyRequest) => boolean | Promise | undefined`) - Optional - Custom authentication function that receives the extracted token and Fastify request object. Must return `true` for valid tokens, `false` for invalid, or a Promise resolving to these values. If provided, `keys` is ignored. - **errorResponse** (`(err: Error) => { error: string }`) - Optional - Function that transforms authentication errors into response objects. The returned object is serialized as the response body. Must return a serializable object. Defaults to `(err) => ({ error: err.message })`. - **contentType** (`string | undefined`) - Optional - HTTP Content-Type header to include in error responses (e.g., `'application/json'`, `'text/plain'`). If not set, no content-type header is added. - **bearerType** (`string`) - Optional - The authorization scheme prefix. Defaults to `'Bearer'`. - **specCompliance** (`'rfc6749' | 'rfc6750'`) - Optional - RFC compliance mode for bearer type matching. Defaults to `'rfc6750'`. - **addHook** (`boolean | 'onRequest' | 'preParsing' | undefined`) - Optional - Hook registration mode. Defaults to `true` (`'onRequest'`). `false` disables auto-registration. `undefined` defaults to `true`. - **verifyErrorLogLevel** (`string`) - Optional - Fastify logger level for logging authentication failures. Defaults to `'error'`. ``` -------------------------------- ### Authentication Logic Comparison Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/api-reference/compare.md Integrates the timing-safe compare function within authentication logic to validate provided tokens against expected tokens. It ensures that token validation, regardless of match or length, takes a consistent amount of time. ```javascript const compare = require('@fastify/bearer-auth/lib/compare') function validateToken(expectedToken, providedToken) { const expected = Buffer.from(expectedToken) const provided = Buffer.from(providedToken) // Always takes same time regardless of match or length difference return compare(expected, provided) } console.log(validateToken('correct', 'correct')) // true console.log(validateToken('correct', 'wrong')) // false console.log(validateToken('abc', 'abcdefg')) // false (takes same time as 'correct'/'wrong') ``` -------------------------------- ### Create Bearer Auth Hook with Keys Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/api-reference/verify-bearer-auth-factory.md Use verifyBearerAuthFactory to create a hook for validating requests with a predefined set of Bearer tokens. This is suitable when you have a fixed list of valid tokens. ```javascript const verifyBearerAuthFactory = require('@fastify/bearer-auth').verifyBearerAuthFactory const verifyAuth = verifyBearerAuthFactory({ keys: new Set(['token-1', 'token-2']) }) // Use as a Fastify hook fastify.addHook('onRequest', verifyAuth) ``` -------------------------------- ### FastifyBearerAuthOptions Interface Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/types.md Defines the configuration options for the @fastify/bearer-auth plugin and its verification hook. Use this to customize token validation, error responses, and hook behavior. ```typescript interface FastifyBearerAuthOptions { keys: Set | string[]; auth?: (key: string, req: FastifyRequest) => boolean | Promise | undefined; errorResponse?: (err: Error) => { error: string }; contentType?: string | undefined; bearerType?: string; specCompliance?: 'rfc6749' | 'rfc6750'; addHook?: boolean | 'onRequest' | 'preParsing' | undefined; verifyErrorLogLevel?: string; } ``` -------------------------------- ### FastifyBearerAuth Plugin Registration Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/types.md This demonstrates how to register the Fastify Bearer Auth plugin with Fastify, providing the necessary options. ```APIDOC ## Register FastifyBearerAuth Plugin ### Description Registers the Fastify Bearer Auth plugin with the Fastify instance. ### Method `fastify.register()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **fastify** (`FastifyInstance`) - The Fastify server instance to register with. - **options** (`FastifyBearerAuthOptions`) - Plugin configuration options. - **done** (`(err?: Error) => void`) - Callback signaling registration completion or failure. ### Usage Example ```typescript import fastifyBearerAuth, { FastifyBearerAuthOptions } from '@fastify/bearer-auth' fastify.register(fastifyBearerAuth, { keys: new Set(['token1', 'token2']) }) ``` ``` -------------------------------- ### authenticate(keys: Buffer[], key: string): boolean Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/api-reference/authenticate.md Authenticates a provided key string against an array of allowed keys (as Buffers) using constant-time comparison to prevent timing attacks. This function is used internally by the verification hook and is exposed for advanced use cases. ```APIDOC ## authenticate(keys: Buffer[], key: string): boolean ### Description Authenticates a provided key string against an array of allowed keys (as Buffers) using constant-time comparison to prevent timing attacks. This function is used internally by the verification hook and is exposed for advanced use cases. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **keys** (Buffer[]) - Required - Array of valid authentication keys, pre-converted to Buffers. These are compared against the provided key. - **key** (string) - Required - The authentication token string to validate. ### Return Type `boolean` Returns `true` if the key matches any of the allowed keys in the array, `false` otherwise. Comparison is always constant-time regardless of key length or match position. ### Request Example ```javascript const authenticate = require('@fastify/bearer-auth/lib/authenticate') const validKeys = [ Buffer.from('secret-key-1'), Buffer.from('secret-key-2'), Buffer.from('secret-key-3') ] // Valid key const result = authenticate(validKeys, 'secret-key-1') console.log(result) // true // Invalid key const result = authenticate(validKeys, 'wrong-key') console.log(result) // false ``` ### Response #### Success Response (200) None explicitly defined, returns boolean. #### Response Example ```json true ``` ```json false ``` ``` -------------------------------- ### Register Bearer Auth with preParsing Hook Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/configuration.md Registers the bearerAuth plugin to use the 'preParsing' hook, allowing authentication checks before the request body is parsed. This is useful for rejecting unauthorized large requests early. ```javascript fastify.register(bearerAuth, { keys: new Set(['token']), addHook: 'preParsing' // Check auth before parsing body }) // Useful for large POST/PUT requests - rejects auth early fastify.post('/upload', (request, reply) => { // Body is parsed only if auth succeeds reply.send({ uploaded: true }) }) ``` -------------------------------- ### Configure Bearer Auth with Default Error Log Level Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/configuration.md This snippet shows how to register the bearerAuth plugin with default settings, where authentication failures are logged at the 'error' level. ```javascript fastify.register(bearerAuth, { keys: new Set(['token']) // verifyErrorLogLevel defaults to 'error' }) // Log output when auth fails: // ERROR: unauthorized: invalid authorization header ``` -------------------------------- ### Registering Bearer Auth with Invalid Key Entry Type Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/errors.md Illustrates the incorrect and correct methods for providing keys to the bearer-auth plugin when non-string values are present in the 'keys' Array or Set. All entries in 'keys' must be strings. ```javascript // ❌ Wrong fastify.register(bearerAuth, { keys: new Set(['token1', 123, 'token2']) }) // ✅ Correct fastify.register(bearerAuth, { keys: new Set(['token1', 'token2', 'token3']) }) ``` -------------------------------- ### Scoped Plugin Registration for Route Protection Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/README.md Illustrates how to register the bearerAuth plugin within a specific scope using `fastify.register` with a prefix, allowing for route-specific authentication. Public routes can be defined outside this scope. ```javascript // Global protection fastify.register(bearerAuth, { keys: new Set(['global-token']) }) // Scoped protection fastify.register(async (fastify) => { fastify.register(bearerAuth, { keys: new Set(['admin-token']) }) }, { prefix: '/admin' }) fastify.get('/public', (request, reply) => { reply.send({ public: true }) // No auth required }) fastify.get('/secure', { preHandler: fastify.verifyBearerAuth, handler: (request, reply) => { reply.send({ data: 'secret' }) // Auth required (global) } }) ``` -------------------------------- ### Default Configuration for Fastify Bearer Auth Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/configuration.md This snippet displays the default configuration object used by the Fastify Bearer Auth plugin when no options are explicitly provided during registration. ```javascript { keys: [], // Empty - no valid tokens by default auth: undefined, // No custom auth function errorResponse: (err) => ({ error: err.message }), contentType: undefined, // No custom Content-Type bearerType: 'Bearer', // Standard OAuth2 bearer specCompliance: 'rfc6750', // Case-sensitive addHook: true, // Register 'onRequest' hook verifyErrorLogLevel: 'error' // Log at error level } ``` -------------------------------- ### RFC6749 Compliance (Case-Insensitive) Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/api-reference/verify-bearer-auth-factory.md Configure the factory to comply with RFC6749, allowing case-insensitive matching for the 'Bearer' token type. This is useful for standard OAuth2 bearer token authentication. ```javascript const verifyBearerAuthFactory = require('@fastify/bearer-auth').verifyBearerAuthFactory const verifyAuth = verifyBearerAuthFactory({ keys: new Set(['mytoken']), specCompliance: 'rfc6749' // Case-insensitive }) // These all work: // Authorization: Bearer mytoken // Authorization: bearer mytoken // Authorization: BEARER mytoken ``` -------------------------------- ### compare(a: Buffer, b: Buffer): boolean Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/api-reference/compare.md Compares two buffers in constant time using Node.js's `crypto.timingSafeEqual()` to prevent timing attacks. If the buffers have different lengths, a dummy comparison is performed to maintain consistent timing before returning `false`. ```APIDOC ## compare(a: Buffer, b: Buffer): boolean ### Description Compares two buffers in constant time using Node.js's `crypto.timingSafeEqual()` to prevent timing attacks. If the buffers have different lengths, a dummy comparison is performed to maintain consistent timing before returning `false`. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **a** (Buffer) - Required - The first buffer to compare - **b** (Buffer) - Required - The second buffer to compare ### Return Type `boolean` Returns `true` if both buffers are equal in content and length, `false` otherwise. The comparison always takes the same amount of time regardless of buffer length or content differences. ### Behavior 1. Compares buffer lengths 2. If lengths differ: - Performs a dummy `timingSafeEqual(a, a)` comparison to maintain timing consistency - Returns `false` 3. If lengths match: - Uses `timingSafeEqual(a, b)` to compare buffer contents - Returns the comparison result (`true` or `false`) ### Usage Examples #### Direct Buffer Comparison ```javascript const compare = require('@fastify/bearer-auth/lib/compare') const validKey = Buffer.from('secret-token') const providedKey = Buffer.from('secret-token') if (compare(validKey, providedKey)) { console.log('Keys match') } else { console.log('Keys do not match') } ``` #### In Authentication Logic ```javascript const compare = require('@fastify/bearer-auth/lib/compare') function validateToken(expectedToken, providedToken) { const expected = Buffer.from(expectedToken) const provided = Buffer.from(providedToken) // Always takes same time regardless of match or length difference return compare(expected, provided) } console.log(validateToken('correct', 'correct')) // true console.log(validateToken('correct', 'wrong')) // false console.log(validateToken('abc', 'abcdefg')) // false (takes same time as 'correct'/'wrong') ``` ``` -------------------------------- ### Handling Errors in Custom Authentication Logic Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/errors.md Implement custom authentication logic using the 'auth' option. Errors during token validation should be logged but return false to indicate an invalid token, rather than throwing. ```javascript fastify.register(bearerAuth, { auth: async (token, request) => { try { const user = await validateToken(token) // Store user in request for use in handlers request.user = user return true } catch (err) { // Log but don't throw - return false for invalid token request.log.debug('Token validation failed: %s', err.message) return false } } }) ``` -------------------------------- ### Registering the Bearer Auth Plugin Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/README.md Register the @fastify/bearer-auth plugin with Fastify, providing a Set of valid bearer tokens for authentication. ```javascript const bearerAuth = require('@fastify/bearer-auth') // Register as Fastify plugin fastify.register(bearerAuth, { keys: new Set(['token-1', 'token-2']) }) ``` -------------------------------- ### verifyBearerAuthFactory Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/types.md Factory function type for creating verification hooks. This allows for the creation of reusable verification logic with specific configurations. ```APIDOC ## verifyBearerAuthFactory ### Description Factory function type for creating verification hooks. Allows for the creation of reusable verification logic with specific configurations. ### Parameters - **options** (`FastifyBearerAuthOptions`) - Configuration for the created verification hook. ``` -------------------------------- ### Custom Error Response Configuration Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/api-reference/fastify-bearer-auth.md Define a custom function to generate the error response when authentication fails. This allows for tailored error messages and structures. ```javascript const fastify = require('fastify')() const bearerAuth = require('@fastify/bearer-auth') fastify.register(bearerAuth, { keys: new Set(['token']), errorResponse: (err) => ({ statusCode: 401, message: 'Unauthorized Access', timestamp: new Date().toISOString() }), contentType: 'application/json' }) ``` -------------------------------- ### RFC6749 Compliance (Case-Insensitive Bearer Type) Source: https://github.com/fastify/fastify-bearer-auth/blob/main/_autodocs/api-reference/fastify-bearer-auth.md Configure the plugin to comply with RFC6749, allowing case-insensitive bearer types in the Authorization header. This is useful for standard OAuth2 bearer token authentication. ```javascript const fastify = require('fastify')() const bearerAuth = require('@fastify/bearer-auth') fastify.register(bearerAuth, { keys: new Set(['token']), specCompliance: 'rfc6749' // Case-insensitive bearer type }) // Both of these requests will succeed: // Authorization: Bearer token // Authorization: bearer token // Authorization: BEARER token ```