This package, `simple-hmac-auth-express`, provides an Express middleware designed for implementing HMAC-based authentication in API endpoints. It acts as a wrapper around the `simple-hmac-auth` core library, integrating its authentication logic seamlessly into the Express request-response cycle. The current stable version is v1.3.0, released in August 2022. Releases appear to be event-driven, primarily driven by updates to its core dependency or maintenance tasks. A key differentiator is its ability to handle request body parsing internally, which is crucial for HMAC signature verification that often requires access to the raw request body before other middleware might consume it. It requires `secretForKey` (a function returning a Promise for the secret) and `onRejected` handlers for failed authentication.
npm install simple-hmac-auth-expressVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to set up `simple-hmac-auth-express` middleware in an Express application. It shows the basic configuration with `secretForKey` and `onRejected` functions, including optional body parsing settings. It provides an example of a protected route and how to access authenticated requests.
Update your `secretForKey` implementation to be an `async` function that directly `return`s the secret (or `null`/`undefined`) or a Promise that resolves with it, rather than using a callback. Example: `secretForKey: async (apiKey) => { /* ... */ return 'SECRET'; }`Review the changelog for `simple-hmac-auth` v4.0.0 for any specific breaking changes that might impact your HMAC signature generation or verification logic. Adjust client-side or server-side implementations as necessary.
Ensure `simple-hmac-auth-express` middleware is placed *before* any other body parsing middleware in your Express application chain. If you need custom body parsing, configure it via the `body` option within the `simple-hmac-auth-express` middleware configuration.
Always ensure your `onRejected` function sends a response (e.g., `res.status(401).json(...)`) or passes an error to the next middleware (`next(error)`) to properly terminate or handle the request. Do not leave the response open.
Refactor `secretForKey` to be an `async` function that returns the secret directly or a `Promise.resolve(secret)`. Example: `secretForKey: async (apiKey) => { /* ... */ return 'mysecret'; }`.Verify that your `onRejected` function explicitly sends a response (e.g., `response.status(401).json(...)`) or calls `next(error)` to propagate the error. Also, check for other middleware inadvertently sending responses.
Double-check the `secretForKey` implementation to ensure it returns the correct secret. Verify that client and server are hashing the *exact* same request components (method, path, headers, raw body). Ensure consistent body parsing, especially if the `body` option is used. Check for significant time differences between client and server.