Simple HMAC Authentication Express Middleware

1.3.0 · active · verified Wed Apr 22

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

import express from 'express';
import auth from 'simple-hmac-auth-express';

const app = express();

app.use(auth({
  // Required: Return a promise that resolves with the secret for the specified API key.
  // This function is async since v1.3.0 and core library v4.0.0.
  secretForKey: async (apiKey) => {
    // In a real application, you would fetch the secret from a database or secure store
    // based on the provided apiKey. For example purposes, we return a hardcoded secret.
    if (apiKey === 'MY_API_KEY') {
      return process.env.HMAC_SECRET_KEY ?? 'my-super-secret-key';
    }
    return null; // API key not found
  },

  // Required: Handle requests that have failed authentication.
  onRejected: (error, request, response, next) => {
    console.error(`Authentication failed for "${request.apiKey}": ${error.message} on ${request.method} ${request.url}`);
    response.status(401).json({
      error: {
        message: error.message || 'Authentication Failed'
      }
    });
  },
  
  // Optional: Handle requests that have passed authentication.
  onAccepted: (request, response) => {
    console.log(`"${request.apiKey}" authenticated request to ${request.method} ${request.url}`);
  },

  // Optional: Body-parser options. The middleware parses the body itself for signature verification.
  // It should be placed before other body parsing middleware.
  body: {
    json: { strict: false, limit: '1mb' },
    urlencoded: { extended: true, limit: '5mb' },
    text: { type: 'application/octet-stream' }
  }
}));

app.get('/protected', (req, res) => {
  res.send(`Hello, authenticated user with API Key: ${req.apiKey}!`);
});

app.post('/protected-data', (req, res) => {
  // Access parsed body if configured in 'body' options
  res.json({ message: 'Data received and authenticated!', data: req.body });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
  console.log('Use MY_API_KEY and hmac signature for /protected and /protected-data');
});

view raw JSON →