Prevent Credential Stuffing in Public REST APIs
A public REST API can accept perfectly valid HTTP requests and still become the entry point for account takeover. Credential stuffing exploits that distinction. The attacker does not need to bypass TLS, inject SQL, or discover a software vulnerability. Instead, automation submits username-and-password combinations obtained from unrelated breaches and looks for accounts that reused credentials.
The defensive objective is not simply to slow requests. It is to make stolen passwords insufficient, make automated verification costly and detectable, and preserve reliable access for legitimate clients. Those goals require decisions at the identity provider, API gateway, authentication service, telemetry pipeline, and incident-response layer. A single IP-based rate limit cannot deliver them.
Understand the attack before choosing controls
Credential stuffing differs from brute-force guessing against one account and password spraying across many accounts. The OWASP Credential Stuffing Prevention Cheat Sheet distinguishes these patterns because their traffic distributions differ. A stolen credential pair may be tested only once. An attacker can distribute many such attempts across different addresses and avoid a simple limit on repeated failures.
A public REST API also exposes more than a browser login page. Mobile applications and partner integrations may authenticate against the same endpoint, while older API versions, token exchanges, or recovery flows provide alternative ways to test a credential. Defending the visible website while leaving a legacy authentication route unprotected creates a bypass.
Map every way a password can be submitted, checked, reset, or exchanged for a session. Include internal calls that become reachable through an edge proxy, administrative portals, and legacy routes. Record which component authoritatively verifies credentials and which component issues a token. Then confirm that every equivalent route shares the relevant account-level attempt state.
The OWASP API Security Top 10 identifies broken authentication as an API risk. The actionable lesson is architectural: identity boundaries matter more than endpoint naming conventions. Attackers target the weakest credential verification path, not necessarily the endpoint your team regards as canonical.
Design independent throttling dimensions
A practical first layer consists of independent limits by account identifier and by source. OWASP's bot-management guidance warns against using only the combined key of source IP and username. Such a counter gives every new pair its own budget and fails to constrain an address that tests a different account on every request.
The account dimension detects repeated attempts against one identity across many network origins. The source dimension detects a client testing many accounts. Additional dimensions may include an IP prefix, authenticated application identity, network provider, device or session signal, and the authentication endpoint itself. The values and thresholds must reflect the product's traffic and abuse patterns; there is no universal safe quota.
Normalize account identifiers consistently before applying a limit. Case-fold email addresses only according to the service's account identity rules; do not accidentally collapse distinct identities. For unknown accounts, use an opaque, bounded identifier-derived key so nonexistent usernames still encounter equivalent defensive behavior without disclosing which accounts exist. Securely hash or otherwise protect identifier keys when they enter shared telemetry or cache infrastructure.
Choose a sliding-window or token-bucket approach when burst handling matters. An edge gateway can reject obvious floods before they consume expensive password-hashing resources, while the identity service holds a second, authoritative counter that follows accounts across gateway instances. Coordinate counters through storage that supports atomic updates and bounded expiration. A per-process dictionary produces inconsistent enforcement under horizontal scaling.
Never treat a configured numerical threshold as proof of security. A strict account threshold can become a denial-of-service tool: an attacker deliberately spends an account's allowance to lock out its owner. Prefer graduated delays, risk-based challenges, and recoverable safeguards, with documented escalation for persistent abuse.
The current NIST SP 800-63B-4 guidance addresses rate limiting on authenticators and describes an upper bound of 100 consecutive failed attempts where its specified requirements apply. That is not a recommended everyday login quota for every product, and it does not replace a product-specific risk assessment. Consumer SaaS teams should distinguish applicable compliance requirements from engineering choices intended to reduce abuse.
Make the stolen password insufficient
Throttling limits how quickly credentials can be tried; it does not invalidate a password that is already correct. Strong authentication provides a separate control. Passwordless passkeys and phishing-resistant cryptographic authenticators change the attacker's problem because possession of a reused password no longer completes the authentication ceremony.
For applications that still use passwords, enforce a suitable second factor, especially for privileged accounts and sensitive operations. Risk-based step-up authentication can be helpful when an unfamiliar device, new network, abnormal velocity, or other verified signal raises concern. However, a risk model should not silently weaken an assurance level promised to users or customers.
The OWASP credential-stuffing guidance recommends multi-factor authentication and explains why CAPTCHAs alone are insufficient. A CAPTCHA may increase friction for some automation, but solver services, accessibility constraints, and non-browser API clients limit its value as a universal gate.
Treat credential verification and high-risk authorization as separate moments. A newly authenticated session might still require a fresh, stronger factor before changing recovery credentials, exporting sensitive information, or issuing a long-lived API token. This reduces the damage an attacker can do with a compromised low-assurance session.
Check compromised passwords when users establish credentials
A password blocklist addresses reuse before it becomes an incident. NIST's password-verifier requirements direct covered verifiers to compare proposed passwords against a list of known commonly used, expected, or compromised values. They also reject routine arbitrary password rotations and composition rules that encourage predictable substitutions.
The Pwned Passwords API provides a documented range-query model: the application can send a short hash prefix and compare returned suffixes locally rather than transmitting the plaintext password or full hash to the service. It can also use an appropriately maintained local corpus. Evaluate availability, privacy, update frequency, and licensing or operational constraints before making an external service part of a critical signup path.
A blocklist is not a universal measure of password quality. Absence from a breach dataset does not guarantee uniqueness, and a password absent today may appear in a future corpus. Combine screening with password manager support, secure password hashing, and strong authentication choices.
Do not log plaintext passwords, full password hashes used for range queries, or raw authentication bodies. Sensitive telemetry can undermine the very control it supports.
Place defenses at the right layers
A robust architecture distinguishes edge controls from identity-specific enforcement. The edge can apply coarse connection and request limits, source reputation, suspicious automation rules, and network-level protections. It should not be the sole authority for per-account enforcement because edge nodes may not share normalized identity state.
The authentication service should validate credentials, enforce account-aware retry policy, and record protected signals about success or failure. The identity provider, where separate, may offer built-in protections that the API must integrate rather than duplicate inconsistently. The session or token service should apply short-lived token policy, revocation mechanisms, and anomaly checks appropriate to the service's threat model.
A conceptual request path is:
client -> edge gateway -> authentication service -> identity store
| |
source controls account controls
|
risk evaluation
|
session / token issuer
|
protected audit events
The separation matters during incidents. Edge rules can be tightened to dampen a current campaign, while account-level safeguards remain active for traffic that passes the edge. Observability can then distinguish mitigated requests from verified malicious successes without conflating blocked traffic with account compromise.
Protect internal identity calls from direct public access. Ensure proxy-forwarded IP metadata is trusted only from controlled upstreams; otherwise attackers may spoof identity and source information used for limits. Fail-safe behavior must be explicit when rate-limit storage is unavailable. Depending on the route and product requirements, a system may temporarily fail closed, degrade to a conservative local safeguard, or route clients through a managed challenge. That is a deliberate availability-versus-security decision, not a default to discover during an outage.
Responses must not reveal the account inventory
An attacker can turn an authentication endpoint into an account discovery oracle if unknown users receive a different message, status code, or timing profile from real accounts. Use generic failed-authentication language and avoid exposing whether a username exists. The same principle applies to password reset and account recovery.
At the protocol level, 429 Too Many Requests communicates throttling. The HTTP problem-details specification, RFC 9457, provides a standard representation for machine-readable API errors, but it does not require exposing internal security counters. A generic error type and a correlation identifier may be sufficient. Avoid publishing which defensive bucket fired, precise remaining attempts, or detailed risk scores.
Return semantics should remain predictable for legitimate automation. Document how clients back off, how interactive authentication challenges are triggered, and which workflows require human intervention. An API that responds identically to every condition may hide security details, but it can also become unusable when error handling is opaque. Keep diagnostic richness in protected server-side logs rather than public responses.
Detect distributed attacks without mistaking every spike for compromise
Credential stuffing often appears as a broad campaign, not an obvious single-user spike. Useful aggregated signals include failed-to-successful authentication ratios, distinct accounts per source, distinct sources per account, rapid device changes, a sharp change in login geography, and correlated login requests across API versions.
Each signal has benign explanations. Large enterprise NAT gateways can put many users behind one address. Travel and privacy networks change geography. A migration may generate a burst of failed logins because clients hold outdated credentials. Use multiple independent signals and test against legitimate traffic before making disruptive enforcement automatic.
Store enough event context for investigation without turning the security platform into a second credential repository. Authentication outcomes, coarse network attributes, pseudonymous account identifiers, endpoint identity, challenge outcomes, and policy decisions are often more useful than full request payloads. Apply access control, retention policy, and auditability to this data.
Measure both attacks blocked and legitimate users affected. A rising denial count may indicate stronger mitigation or merely more incoming noise. Track successful account takeovers through independently verified incidents, verified user reports, and suspicious post-login changes. Distinguish detections, interventions, and confirmed compromise in dashboards.
Test bypasses and operational failure modes
Before a rollout, use a controlled test environment with synthetic accounts and authorized test traffic. Exercise account-targeted attempts from multiple source addresses and broad account sweeps from one address. Confirm that each independently triggers the intended control. Check the same cases through every login route, API version, and token exchange path.
Then test edge cases: case variations in user identifiers, unknown usernames, proxy-header spoofing, cache expiry, concurrent requests, rolling deployments, and failures in shared rate-limit storage. Verify that counters are atomic, avoid accidental unbounded key creation, and expire according to retention policy. Evaluate how quickly a genuine user can recover from a malicious lockout.
A particularly important test is successful reuse of a known test password. If that result leads directly to a powerful session despite low-risk scoring and no additional factor, throttling has not solved the fundamental credential-reuse problem. Exercise privileged changes and token issuance after initial login to verify step-up protections.
Observe the effect on real clients through staged enforcement: first measure candidate rules without blocking; then challenge or slow a narrowly defined cohort; finally enforce with an explicit rollback path. Record false positives as security defects, not merely customer-support tickets.
Build an incident response that can distinguish abuse from takeover
When a campaign is detected, the response should move through containment, impact assessment, and recovery. Containment may involve stronger per-source controls, temporary challenges, tighter account-level budgets, and added step-up requirements for sensitive actions. Changes should be time-bounded and reviewable so emergency policies do not become permanent unexplained friction.
Impact assessment asks a different question from traffic mitigation: which accounts actually authenticated using suspicious activity, and what did those sessions do afterward? Correlate authentication events with token issuance, account profile changes, credential resets, and sensitive data access. Do not label every failed attempt as a compromised account.
For confirmed or credible account takeover, revoke relevant sessions and tokens, guide affected users through secure recovery, and investigate whether new persistent credentials were created. Review whether downstream APIs accepted tokens after the authentication system flagged risk. Communicate with users based on established facts rather than assuming a detected campaign implies a breach of the API provider's own password database.
Make an explicit engineering trade-off
The right posture is layered and measurable. Start with a complete inventory of credential-verifying endpoints, independently keyed account and source throttling, breached-password screening at password establishment, and a stronger factor for sensitive access. Add behavioral automation defenses and adaptive challenges where traffic evidence justifies their complexity.
The hard design problem is not selecting a vendor threshold. It is maintaining consistent policy across distributed systems while preserving access for people behind shared networks, users of assistive technology, and legitimate machine clients. A defensible system knows what a request is allowed to prove, what extra evidence is required when risk rises, how interventions are audited, and how failures are recovered without creating new account-discovery or denial-of-service vulnerabilities.