This package provides a plug-and-play HTTP Basic Authentication solution designed for use with the Fastify web framework. It supports checking credentials against static user lists or through custom synchronous or asynchronous authorizer functions. As of version 0.0.2, it emphasizes secure credential comparison with a `safeCompare` utility to prevent timing attacks. While its README initially showed Express.js examples, the package is explicitly built for Fastify. It ships with TypeScript types, ensuring type safety for Fastify applications. This plugin is distinct from the `@fastify/basic-auth` core plugin, offering a different API for integrating basic authentication.
npm install fastify-basic-auth-middlewareVerified import paths — ran on the pinned version, not inferred.
This example sets up a Fastify server with basic authentication using static user credentials. It protects the `/protected` route, demonstrating how the `fastify-basic-auth-middleware` integrates with Fastify's plugin system and hooks.
Ensure you are using `fastify.register(basicAuthPlugin, options)` to integrate this plugin with your Fastify instance. For `app.use()` style middleware, Fastify v3+ requires `@fastify/express` or `middie` plugins, but this specific package is a native Fastify plugin.
Always use the provided `basicAuth.safeCompare(userInput, secret)` function for comparing user-provided credentials with secrets within your custom authorizer. Also, use bitwise logical operators (`|`, `&`) instead of standard (`||`, `&&`) to avoid short-circuiting that could reveal timing information.
For asynchronous `authorizer` functions, pass `authorizeAsync: true` in the options object and ensure your `authorizer` function calls a callback (`cb(error, isApproved)`) or returns a Promise as per Fastify's async hook patterns.
Consult the documentation for the specific package you intend to use. If you want the core plugin, install `@fastify/basic-auth`. If you explicitly chose `fastify-basic-auth-middleware`, follow its specific API for plugin registration and usage.
Replace `app.use(basicAuth(...))` with `fastify.register(basicAuthPlugin, { ...options... })` to correctly register the plugin with Fastify. Hooks like `fastify.addHook('preHandler', ...)` can then utilize the plugin's functionality.Ensure that `authorizeAsync: true` is set in the options object when registering the plugin. Additionally, verify that your asynchronous authorizer correctly calls the provided `cb(null, true)` for success or `cb(null, false)` for failure (or resolves/rejects a Promise if using `async/await`).
Augment the `FastifyRequest` interface to include the `auth` property. Create a declaration file (e.g., `src/types/fastify.d.ts`) with:
```typescript
declare module 'fastify' {
interface FastifyRequest {
auth: {
user: string;
password?: string;
};
}
}
```No dependency data recorded yet.