Description
Password verification in Express does not limit how often a client can submit a login request. Unrestricted attempts let someone repeatedly try passwords or previously leaked credentials.
Potential impact
A correct guess or reused credential may expose the account. Without records of repeated failures, suspicious activity is harder to detect and investigate.
Remediation
- Apply middleware such as
express-rate-limitbefore the login handler to limit requests regardless of the authentication outcome. - Also track failed attempts by account and IP address, and by device where appropriate. Use a delay, temporary lockout, or CAPTCHA when your failure threshold is reached.
- Log account lock and unlock events and configure security alerts.
Examples
These route excerpts omit body parsing, rateLimit initialization, user lookup and error handling. Configure trusted proxy IP handling, IPv6 address grouping and shared counters across application instances for the deployment.
Before
javascript
app.post("/login", async (req, res) => {
const user = await loadUser(req.body.username);
const ok = await bcrypt.compare(req.body.password, user.passwordHash);
res.json({ ok });
});
After
javascript
const loginLimiter = rateLimit({
windowMs: 60_000,
max: 5,
keyGenerator: (req) => `${req.ip}:${req.body.username ?? ""}`,
});
app.post("/login", loginLimiter, async (req, res) => {
const user = await loadUser(req.body.username);
const ok = await bcrypt.compare(req.body.password, user.passwordHash);
res.json({ ok });
});
Explanation:
- Before: Every login request reaches password verification without an attempt limit.
- After: The same IP address and username pair can make five requests per minute, counting successes and failures. Account locks and device limits are separate controls. Add independent counters for an account-wide or IP-wide limit.