
Security News
Attackers Are Hunting High-Impact Node.js Maintainers in a Coordinated Social Engineering Campaign
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.
secure-auth-node
Advanced tools
A lightweight JWT authentication and role-based access control middleware for Node.js (Express).
A lightweight and flexible authentication module for Node.js projects, built with JWT and MongoDB. Easily add secure access token, refresh token, and role-based authentication to your Express apps.
secure-auth-node?Most authentication setups are repetitive. This library saves time by offering a plug-and-play JWT system with role-based access and refresh token support — without forcing you to change your app structure.
npm install secure-auth-node
✅ Also ensure
mongooseis installed in your project:
npm install mongoose
🔰 Minimal example:
const { generateAccessToken } = require("secure-auth-node");
// server.js
require("dotenv").config();
const express = require("express");
const {
connectToMongoDB,
initAuthConfig,
generateAccessToken,
generateRefreshToken,
refreshAccessToken,
authMiddleware,
roleMiddleware,
} = require("secure-auth-node");
const app = express();
app.use(express.json());
// ✅ Connect to MongoDB
connectToMongoDB();
// ✅ Initialize Auth Config
initAuthConfig({
accessTokenSecret: process.env.ACCESS_TOKEN_SECRET,
refreshTokenSecret: process.env.REFRESH_TOKEN_SECRET,
});
// ✅ Fake user DB
const users = [
{ id: 1, username: "admin", role: "admin" },
{ id: 2, username: "user", role: "user" },
];
// 🔐 Login route
app.post("/login", async (req, res) => {
const { username } = req.body;
const user = users.find((u) => u.username === username);
if (!user) return res.status(401).json({ message: "Invalid user" });
const accessToken = generateAccessToken(user);
const refreshToken = await generateRefreshToken(user);
res.json({ accessToken, refreshToken });
});
// 🔁 Refresh token
app.post("/refresh", async (req, res) => {
try {
const { token } = req.body;
const newAccessToken = await refreshAccessToken(token);
res.json({ accessToken: newAccessToken });
} catch (err) {
res.status(403).json({ message: "Invalid refresh token" });
}
});
// 👤 Protected route
app.get("/dashboard", authMiddleware, (req, res) => {
res.send(`Hello, ${req.user.username}`);
});
// 🛡️ Admin-only route
app.get("/admin", authMiddleware, roleMiddleware(["admin"]), (req, res) => {
res.send("Welcome Admin!");
});
app.listen(3000, () => console.log("✅ Server running on port 3000"));
Create a .env file in your project root directory with the following keys:
MONGO_URI=your-mongodb-uri
ACCESS_TOKEN_SECRET=your-access-token-secret
REFRESH_TOKEN_SECRET=your-refresh-token-secret
💡 You can generate token secrets using tools like jwt.io or
openssl rand -hex 32.
| Function | Description |
|---|---|
connectToMongoDB() | Connect to MongoDB using process.env.MONGO_URI |
initAuthConfig(config) | Set secrets and token expiry |
generateAccessToken(user) | Returns JWT access token |
generateRefreshToken(user) | Returns JWT refresh token and stores it in DB |
refreshAccessToken(token) | Validates refresh token and returns a new access token |
authMiddleware | Protects routes, validates access token |
roleMiddleware(['role']) | Grants access to users with specific roles |
These are sample API routes provided for testing and demonstration purposes (from the test/server.js file). You can freely customize them to fit your project.
🛠️ This package only handles authentication logic like generating tokens, verifying tokens, and role checking — it does not control how your users log in or how your routes are structured.
POST /login
📦 Request Body (JSON format):
{
"username": "admin"
}
✅ You can customize fields like:
{
"username": "admin",
"password": "your-password"
}
POST /refresh
📦 Request Body (JSON format):
{
"token": "your-refresh-token"
}
The library uses
const { token } = req.body, so structure must match.
GET /dashboard
Headers:
Authorization: Bearer your-access-token
GET /admin
Headers:
Authorization: Bearer your-access-token
Only users with the role "admin" can access this.
Refresh tokens are securely stored in your MongoDB using a simple schema.
connectToMongoDB() in your appinitAuthConfig({
accessTokenSecret: 'your-secret',
refreshTokenSecret: 'your-refresh-secret',
accessTokenExpiry: '25m', // default is '15m'
refreshTokenExpiry: '10d' // default is '7d'
});
This project is licensed under the Apache-2.0 License.
Contributions, bug reports, and feature requests are welcome! Feel free to fork the repo and open a pull request, or open an issue.
Author: Pratyush Tripathi For help, ideas, or questions, open an issue on GitHub
FAQs
A lightweight JWT authentication and role-based access control middleware for Node.js (Express).
We found that secure-auth-node demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.

Security News
Axios compromise traced to social engineering, showing how attacks on maintainers can bypass controls and expose the broader software supply chain.

Security News
Node.js has paused its bug bounty program after funding ended, removing payouts for vulnerability reports but keeping its security process unchanged.