Express Smart Authentication Middleware

0.21.0 · active · verified Wed Apr 22

This package, `smart-auth-middleware`, is an Express.js middleware designed for authenticating incoming requests by validating JSON Web Tokens (JWTs) against an external Identity Service (IDS). It integrates with `jwks-rsa` for fetching JSON Web Key Sets and `express-jwt` for the core JWT verification process. Currently at version 0.21.0, it is in active development, implying that breaking changes might occur more frequently between minor versions as it approaches a stable 1.0 release. The middleware provides a lifecycle with `authPreCheck` for initial validation, `jwtVerify` for token verification and setting user information on `req.user`, and `authPostCheck` to ensure verification success. Its key differentiators include built-in support for JWKS endpoints and configurable options for issuer, audience, and ignored paths, streamlining JWT-based authentication in Express applications.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to integrate `smart-auth-middleware` into an Express application, configure essential options, protect routes, and handle common authentication errors.

import express from 'express';
import authentication from 'smart-auth-middleware';

const app = express();
const router = express.Router();

// Ensure environment variables are set or provide fallbacks
const options = {
    IDENTITY_SERVICE_URL: process.env.IDENTITY_SERVICE_URL ?? 'http://localhost:3000/identity',
    ISSUER: process.env.JWT_ISSUER ?? 'your-issuer-url',
    AUDIENCE: process.env.JWT_AUDIENCE ?? 'your-audience',
    ignorePaths: [ '/healthcheck', '/ping' ]
};

// Apply the authentication middleware to all routes under '/'
// All routes after this middleware will require a valid JWT, except ignoredPaths
app.use('/', authentication(options), router);

router.get('/secure-data', (req, res) => {
  // req.user will be populated by the middleware if token is valid
  if (req.user) {
    res.status(200).json({ message: 'Access granted to secure data', user: req.user });
  } else {
    res.status(401).json({ message: 'Unauthorized: req.user not found' });
  }
});

router.get('/healthcheck', (req, res) => {
  res.status(200).send('Service is healthy');
});

// Basic error handling middleware for express-jwt errors
app.use((err, req, res, next) => {
  if (err.name === 'UnauthorizedError') {
    res.status(401).json({ message: 'Invalid token: ' + err.message });
  } else {
    next(err);
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
  console.log('Test with: curl -H "Authorization: Bearer <YOUR_JWT>" http://localhost:3000/secure-data');
  console.log('Or: curl http://localhost:3000/healthcheck');
});

view raw JSON →