Description
In jsonwebtoken 9.x, an empty key alone does not disable signature verification. The first example accepts unsigned tokens because it supplies an empty key and explicitly allows none in algorithms.
Potential impact
Trusting unsigned sub, role or admin claims can give someone access to protected APIs and data as another user or an administrator.
Remediation
decode()only reads a token. For authentication and authorization, pass a trusted key and a server-defined algorithm allow-list toverify(). Use a strong shared secret forHS256or a public key forRS256, and excludenone.- Check issuer (
iss), audience (aud) and expiration (exp). If expiration is required, reject tokens withoutexpas well.
Examples
Before
javascript
const express = require("express");
const jwt = require("jsonwebtoken");
const app = express();
// Before: verify without a key (for example, an empty string)
app.get("/profile", (req, res) => {
const auth = req.headers.authorization || "";
const token = auth.replace(/^Bearer\s+/i, "");
// BAD: an empty key and explicit none allowance permit unsigned tokens
const payload = jwt.verify(token, "", { algorithms: ["HS256", "none"] });
// Forged payloads may gain access
res.json({ user: payload.sub, admin: payload.admin });
});
app.listen(3000);
After
javascript
const express = require("express");
const jwt = require("jsonwebtoken");
const app = express();
const JWT_SECRET = process.env.JWT_SECRET; // Store securely
app.get("/profile", (req, res) => {
const m = (req.headers.authorization || "").match(/^Bearer\s+(.+)$/i);
if (!m) return res.status(401).send("Missing token");
try {
const payload = jwt.verify(m[1], JWT_SECRET, {
algorithms: ["HS256"], // Allow only the required algorithm, excluding none
issuer: "auth.example.com", // Validate iss
audience: "my-api", // Validate aud
});
return res.json({ user: payload.sub });
} catch (e) {
return res.status(401).send("Invalid token");
}
});
app.listen(3000);
The handler verifies HS256 with JWT_SECRET, checks issuer and audience, and returns 401 on failure. It checks exp when present and accepts tokens that omit it if the other checks pass.