Credential stuffing: how it works and 7 ways to stop it
Credential stuffing is an automated attack where bots replay username and password pairs leaked from one site against your login, betting that people reused the password. You stop it by layering defenses: MFA or passkeys
Credential stuffing is an automated attack where bots replay username and password pairs leaked from one site against your login, betting that people reused the password. You stop it by layering defenses: MFA or passkeys, breached-password checks, bot detection, rate limits and lockout, risk signals, monitoring, and unique passwords, because no single control holds on its own.
Disclosure: I work at Frontegg. This is a shorter, code-first version of our credential stuffing guide. The defenses below work with any stack.
Why it works
Password reuse is the whole business model. Verizon's 2025 Data Breach Investigations Report (DBIR article) found:
- Compromised credentials were the initial access vector in 22% of breaches it reviewed.
- On devices infected with infostealer malware, only 49% (median) of a given user's passwords across different services were distinct from each other.
- In SSO authentication logs, the median daily share of credential stuffing was 19% of all attempts, up to 25% at enterprise-sized companies. The highest single day was 44%.
How an attack runs
- Collect credentials. Buy or download breach dumps; infostealer logs add passwords lifted from browsers.
- Automate logins. Bots try each pair against your login page or API, spread across proxies, with spoofed browser fingerprints and CAPTCHA-solving services.
- Find hits. Most attempts fail. A small success rate at high volume still yields many working accounts.
- Use or sell access. Drain stored value, steal data, place orders, or resell the logins.
Notice step 2: each pair is usually tried once per account. That's why a per-account failure counter alone misses it.
Stuffing vs brute force vs password spraying
| Credential stuffing | Brute force | Password spraying | |
|---|---|---|---|
| Attacker starts with | Breached username/password pairs | One target username | A list of usernames |
| Guessing pattern | Each known pair, once, on a new site | Many passwords, one account | A few common passwords, many accounts |
| Works because | Password reuse | Weak or short passwords | Common passwords |
| Attempts per account | One or a few | Many | One or a few |
| Why it's hard to spot | Looks like real users with valid-looking credentials | Rarely hard: per-account volume is high | Low per-account volume stays under lockout limits |
| Best defenses | MFA, breached-password checks, bot detection | Lockout and rate limits, MFA | Banning common passwords, MFA, cross-account monitoring |
7 ways to stop it
1. Require MFA, or go passwordless
A stolen password is useless if it isn't enough to sign in. OWASP calls MFA the strongest defense against credential stuffing. If prompting every login is too much friction, trigger MFA on risk: new device, unusual location, or an IP that has tried many accounts. Passkeys remove the reusable password entirely.
2. Reject breached passwords
Check new passwords against known breach corpora at sign-up, password change and reset (and optionally at login). Have I Been Pwned's Pwned Passwords range API uses k-anonymity: you send only the first 5 hex characters of the SHA-1 hash and compare the returned suffixes locally.
// breached.js
const crypto = require("node:crypto");
async function isBreached(password, { fetchFn = fetch, failOpen = true } = {}) {
const sha1 = crypto.createHash("sha1").update(password, "utf8").digest("hex").toUpperCase();
const prefix = sha1.slice(0, 5);
const suffix = sha1.slice(5);
try {
const res = await fetchFn(`https://api.pwnedpasswords.com/range/${prefix}`, {
headers: { "Add-Padding": "true", "User-Agent": "my-app-signup" },
});
if (!res.ok) throw new Error(`HIBP returned ${res.status}`);
const body = await res.text();
return body.split(/\r?\n/).some((line) => {
const [hashSuffix, count] = line.trim().split(":");
return hashSuffix?.toUpperCase() === suffix && Number(count) > 0; // padded rows have count 0
});
} catch (err) {
if (failOpen) return false; // don't block sign-ups if the API is down; log it
throw err;
}
}
module.exports = { isBreached };
Add-Padding: true makes every response 800 to 1,000 rows so response size doesn't leak the prefix; padded rows have a count of 0, which is why the code checks count > 0. Decide deliberately whether to fail open or closed when the API is unreachable.
3. Detect bots, and treat CAPTCHA as one layer
Bots drive the attack, so score sign-in traffic and challenge what looks automated. OWASP warns that CAPTCHAs are imperfect and that tools and solving services can bypass them; watch your solve rate, since an unusually high one suggests automated solving. Connection fingerprints (TLS, HTTP/2) are harder to spoof than client-side device fingerprints.
4. Rate-limit and lock out on more than one key
Count failures per account (brute force) and per IP, and track how many different usernames one IP touches (stuffing). Here's a minimal in-memory version; in production, back it with Redis or similar.
// limiter.js: in-memory for the example (keys are never evicted); use Redis or similar in production
class SlidingWindow {
constructor(windowMs) {
this.windowMs = windowMs;
this.events = new Map(); // key -> [{ t, value }]
}
add(key, value = null, now = Date.now()) {
const list = (this.events.get(key) ?? []).filter((e) => now - e.t < this.windowMs);
list.push({ t: now, value });
this.events.set(key, list);
}
count(key, now = Date.now()) {
return (this.events.get(key) ?? []).filter((e) => now - e.t < this.windowMs).length;
}
distinct(key, now = Date.now()) {
const live = (this.events.get(key) ?? []).filter((e) => now - e.t < this.windowMs);
return new Set(live.map((e) => e.value)).size;
}
}
const FIFTEEN_MIN = 15 * 60 * 1000;
const failuresByAccount = new SlidingWindow(FIFTEEN_MIN);
const failuresByIp = new SlidingWindow(FIFTEEN_MIN);
const usernamesByIp = new SlidingWindow(FIFTEEN_MIN);
// Example thresholds: tune them on your own traffic.
const LIMITS = { perAccount: 5, perIp: 20, distinctUsernamesPerIp: 10 };
const normalize = (username) => username.trim().toLowerCase();
function checkLogin({ ip, username }, now = Date.now()) {
const user = normalize(username); // "Alice" and "alice" must share one counter
usernamesByIp.add(ip, user, now);
if (failuresByAccount.count(user, now) >= LIMITS.perAccount) return "lock"; // brute force on one account
if (failuresByIp.count(ip, now) >= LIMITS.perIp) return "block"; // noisy IP
if (usernamesByIp.distinct(ip, now) > LIMITS.distinctUsernamesPerIp) return "challenge"; // stuffing: one IP, many accounts
return "allow";
}
function recordFailure({ ip, username }, now = Date.now()) {
failuresByAccount.add(normalize(username), null, now);
failuresByIp.add(ip, null, now);
}
module.exports = { checkLogin, recordFailure, SlidingWindow, LIMITS };
Wire it into the login route, and return the same error whether or not the account exists so the endpoint can't be used to enumerate users:
// app.js
const express = require("express");
const { checkLogin, recordFailure } = require("./limiter");
function createApp({ verifyPassword }) {
const app = express();
// Only behind a proxy/load balancer: set your real hop count so req.ip is the client, not the proxy.
// Not behind one? Remove this line, or clients can spoof req.ip with X-Forwarded-For.
app.set("trust proxy", 1);
app.use(express.json());
app.post("/login", async (req, res) => {
const { username = "", password = "" } = req.body;
const ctx = { ip: req.ip, username };
const decision = checkLogin(ctx);
if (decision === "block" || decision === "lock") {
res.set("Retry-After", "900");
return res.status(429).json({ error: "Too many attempts. Try again later." });
}
if (decision === "challenge") {
// Hand off to your MFA or CAPTCHA step here; this stub only signals it.
return res.status(401).json({ error: "Additional verification required", mfa: true });
}
// verifyPassword should hash a dummy value for unknown users so timing doesn't reveal who exists.
const ok = await verifyPassword(username, password);
if (!ok) {
recordFailure(ctx);
// Same message whether the user exists or not: no account enumeration.
return res.status(401).json({ error: "Invalid username or password" });
}
return res.json({ ok: true });
});
return app;
}
module.exports = { createApp };
Two caveats. Attackers rotate through proxy networks, so per-IP limits slow them down rather than stop them; OWASP says IP blocking shouldn't be your primary defense. Hard account locks can be abused to lock real users out, so pair them with a self-service unlock email or prefer a challenge. And cover every endpoint that accepts credentials (password reset, token endpoints, mobile APIs), not just /login.
5. Use device, IP and location signals
A login from a new device, a hosting-provider IP, or a location the user couldn't have reached since their last sign-in is a reason to ask for a second factor, not necessarily to block. Device fingerprints are client-supplied and spoofable, so use them as one signal among several.
6. Monitor sign-in patterns and tell users
Alert on the shape of an attack, not single requests: a rising failure rate across many accounts, a spike in distinct usernames per IP or network, or a jump in breached-password hits. Notify users about meaningful events, such as a correct password followed by a failed MFA check, and let them see and end active sessions. Don't email on every failed attempt, or people learn to ignore you.
7. Encourage unique passwords and password managers
Reuse is the root cause. Allow long passwords and paste so password managers work, and explain in the UI why a breached password was rejected.
The Frontegg option
If you'd rather not build and tune all of this yourself, Frontegg's Security Center has built-in security rules that map to several of the defenses above, including bot detection, breached password, brute force protection, new device, suspicious IPs and impossible travel. Each rule has an action (such as allow, challenge with MFA, block or lock), and on supported rules (such as bot detection or suspicious IPs) overrides let you force a different action for specific users, tenants or IPs, for example to keep QA accounts out of bot detection.
Checklist
- [ ] MFA available for everyone, and triggered on risky sign-ins
- [ ] Passwords checked against breach data at sign-up, change and reset
- [ ] Bot detection in front of login, with CAPTCHA as one layer at most
- [ ] Failures counted per account and per IP, plus distinct usernames per IP
- [ ] Same error message, status and similar response time for unknown user and wrong password
- [ ] Extra verification on new devices, suspicious IPs and impossible travel
- [ ] Self-service unlock for locked accounts
- [ ] Alerts on aggregate failure patterns, and user notifications for real risk events
- [ ] Every credential-accepting endpoint covered, not just
/login - [ ] Long passwords and paste allowed, so password managers work
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.