Registry / auth-security / smart-auth-middleware

smart-auth-middleware

JSON →
library0.21.0jsnpmunverified

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.

npm install smart-auth-middleware
INSTALL
IMPORT
SIG · SMART-AUTH-MIDDLEW
S
smart-auth-middleware
auth-securityjavascriptv0.21.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

authentication
import authentication from 'smart-auth-middleware';
import { authentication } from 'smart-auth-middleware';
The library primarily exports a default function. While the README shows CommonJS, this is the correct ESM import assuming dual package support.
authentication
const authentication = require('smart-auth-middleware');
const { authentication } = require('smart-auth-middleware');
As per documentation, this is the correct CommonJS `require` statement for the default exported function.
Auth Options
// No direct import for options object, it's passed directly to the middleware function
import { options } from 'smart-auth-middleware';
Configuration options are passed as an object directly to the `authentication` middleware function, not imported separately.

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'); });
Debug
Known issues
breakingAs a package in the `0.x.x` version series, `smart-auth-middleware` may introduce breaking changes in minor versions (e.g., from 0.20.x to 0.21.x) without adhering to semantic versioning for major changes. Always review changelogs when updating.
fix
Thoroughly review the package's `CHANGELOG.md` or release notes before updating minor versions, especially in production environments.
affects: >=0.1.0
gotchaThe `IDENTITY_SERVICE_URL` option is mandatory. If it's not provided or is misconfigured, the middleware's `authPreCheck` method will throw an error, preventing the application from starting or processing requests.
fix
Ensure `IDENTITY_SERVICE_URL` is always present and correctly points to your Identity Service. Use environment variables for sensitive or deployment-specific configurations.
affects: >=0.1.0
gotchaError handling for `UnauthorizedError` from the underlying `express-jwt` library must be explicitly implemented as an Express error handling middleware (`app.use((err, req, res, next) => { ... })`). Failing to do so will result in unhandled exceptions.
fix
Add a dedicated Express error handling middleware to catch `UnauthorizedError` and other potential errors thrown by the authentication process, providing a user-friendly response.
affects: >=0.1.0
gotchaThe middleware expects a JWT in the `Authorization` header with a `Bearer` prefix (e.g., `Authorization: Bearer <token>`). Using incorrect header names or token formats will result in authentication failure.
fix
Clients should send JWTs in the standard `Authorization: Bearer <token>` format. Verify client-side implementation matches this expectation.
affects: >=0.1.0
Errors
Common errors & fixes
Error: IDENTITY_SERVICE_URL is mandatory configuration.
The `IDENTITY_SERVICE_URL` option was not provided or was an empty string when initializing the middleware.
fix
Ensure `IDENTITY_SERVICE_URL` is set to a valid URL in the options object passed to `authentication()`.
UnauthorizedError: No authorization token was found
The `Authorization` header was missing or empty in the incoming HTTP request.
fix
The client must provide an `Authorization` header with a valid JWT, prefixed by `Bearer` (e.g., `Authorization: Bearer YOUR_JWT_TOKEN`).
UnauthorizedError: Invalid token
The provided JWT was malformed, expired, had an incorrect signature, or did not pass other validation checks (e.g., issuer, audience).
fix
Verify that the JWT is correctly formed, has not expired, is signed by a trusted issuer, and matches the expected audience configured in the middleware options.
Upgrade
Version history
0.21.0latest on npm
Audit
Dependencies
jwks-rsarequiredUsed internally to retrieve RSA public keys from a JWKS endpoint for token verification.
express-jwtrequiredProvides the core JWT authentication logic, including token parsing and signature verification.
Agent activity
9 hits · last 30 days
node
6
OpenAI (training)
2
Resources
smart-auth-middleware — npm install smart-auth-middleware · libregistry