Siti has forgotten her password. At the same time, in an internet cafe, someone is trying to guess Siti's password over and over. Both happen at the same login form, and this lesson deals with both.
Account recovery: Siti forgets her password, proves she owns the account through her email, then sets a new password. Lockout: after too many wrong passwords, the next attempts are held back for a while. Picture a school locker with a combination lock. Get the combination wrong five times and the locker refuses the next try for 15 minutes, not forever. If it locked forever, any prankster could make a friend's locker impossible to open. Forgot the combination? The caretaker gives the owner a one-time key, the combination is changed, and every old key stops working at once. In this picture, the locker is the account, the combination is the password, and the caretaker is the server. The one-time key is the reset token sent by email, and the old keys that stop working are the sessions that get revoked.
Forgot password: the flow
Here is the HTTP conversation in School Portal, exactly what the Lab shows (the token in the Lab is random):
POST /forgot-password HTTP/1.1
Host: portal.school.test
{"email": "[email protected]"}
HTTP/1.1 200 OK
{"message": "If that email is registered, a password reset link is on its way."}
POST /reset-password HTTP/1.1
Host: portal.school.test
{"token": "BIrrdlGOeVSVLLnsip3iOl4JlDLm9xGZVTNnygSkRCY", "email": "[email protected]", "password": "Grade11-Science2-safe"}
HTTP/1.1 200 OK
{"message": "Your password has been changed. Please log in again."}
- The reset token is made exactly the way the previous lesson, Magic Link Authentication, makes its token: 32 random bytes from
crypto.getRandomValues, base64url in the email link, and only its SHA-256 is stored. The difference is its life: 60 minutes, because people need time to think of a new password. - The answer to
POST /forgot-passwordis always the same, registered email or not. A token that isn't found, was already used, or has expired gets422(the data sent can't be processed) with one message: "This reset link no longer works. Ask for a new one."
After the reset: revoke every session, tell the owner
This is what the server does when it receives POST /reset-password:
async function resetPassword(token, newPassword, now) {
const row = resetTokens.get(await sha256Hex(token));
if (!row || row.usedAt !== null || now >= row.expiresAt) return 422;
row.usedAt = now; // single use
const user = users.get(row.userId);
user.passwordHash = await hashPassword(newPassword); // the Password Hashing lesson
for (const [id, session] of sessions) {
if (session.userId === user.id) sessions.delete(id); // every device logs out
}
sendEmail(user.email, "Your School Portal password was just changed. Not you? Contact the school admin.");
return 200;
}
resetTokensis the table of reset tokens.sha256Hexand its three checks are the same asverifyLinkin the Magic Link Authentication lesson.hashPasswordis the slow, salted hash from the Password Hashing lesson.- The
sessionsloop deletes every one of Siti's sessions. She has three, on her laptop, her phone and the lab computer (as in the Auth Best Practices lesson). After the reset: zero. Changing the password alone doesn't sign out someone who had already logged in with the old password: their session is still valid. If School Portal uses refresh tokens, revoke all of them too (the Refresh Token Rotation lesson). sendEmailtells the owner. If someone other than Siti did the reset, Siti finds out right away and can report it.
Lockout: a temporary pause per email and IP
The easiest approach is "5 wrong passwords and the account is locked until an admin opens it". It has a big problem: anyone who knows Siti's email can stop Siti from logging in, with nothing more than five wrong passwords. There are two fixes. First, the pause is temporary, not permanent. Second, only the pair of email and failing IP is held back, not the whole account. Compare:
| Option | What is held back | When it opens |
|---|---|---|
| Permanent lock per account | Siti's account, from anywhere | when an admin opens it |
Pause per email|IP |
only the pair of Siti's email and the failing IP | on its own, 15 minutes after its failures |
The server counts failures per counting key, a tag that identifies the sender: here the pair of email and IP. For example, from an internet cafe computer, someone types Siti's email with a wrong password five times. A minute later Siti logs in from home with the right password. With a pause per email|IP, five failures from the internet cafe only hold back the pair of Siti's email and the cafe's IP, [email protected]|198.51.100.23. Siti logs in from home (203.0.113.7) under a different counting key, its count is empty, so she can get in. With a permanent lock per account, Siti is locked out too, even with the right password.
This pause is throttling: slowing down, not locking. Someone who keeps switching IPs does get a fresh allowance of attempts on each IP. The next layers, a limit per IP and a captcha after a few failures, are in the Rate Limiting for Authentication lesson.
Sliding window: counting the failures of the last 15 minutes
This code records the time of each failure per counting key, and checks them before the password is checked:
const WINDOW = 15 * 60 * 1000;
const THRESHOLD = 5;
const failures = new Map(); // "email|ip" -> [failure time, ...]
function recordFailure(key, now) {
if (!failures.has(key)) failures.set(key, []);
failures.get(key).push(now);
}
function isLockedOut(key, now) {
const recent = (failures.get(key) || []).filter((t) => t > now - WINDOW); // the last 15 minutes
failures.set(key, recent); // old ones are dropped
return recent.length >= THRESHOLD;
}
function clearFailures(key) {
failures.delete(key); // called when a login succeeds
}
function login(email, password, ip, now) {
const key = `${email.toLowerCase()}|${ip}`;
if (isLockedOut(key, now)) return 429; // the password is not even checked
if (!checkPassword(email, password)) {
recordFailure(key, now); // recorded for any email, registered or not
return 401;
}
clearFailures(key);
return 200;
}
- Sliding window (a window that moves along with the clock): only the failures of the last 15 minutes count, measured back from now. Old failures leave the window one by one, so the pause ends on its own, and Siti who got it wrong 4 times and then took an hour's break starts from zero again. A fixed counter (a count that only goes up) never forgets: last month's failures still count, and the account stays locked until someone clears the count.
>= THRESHOLD: the fifth failure already starts the pause. The sixth attempt gets429without the password being checked.
This is a trace from the Lab:
| Time | From | What happens | Failures in the last 15 minutes | Answer |
|---|---|---|---|---|
| 07:00 | internet cafe | wrong password number 1 to 5 | 1 to 5 | 401 |
| 07:01 | internet cafe | tries again | 5 | 429, Retry-After: 840 |
| 07:02 | Siti's home | right password | 0 (a different counting key) | 200 |
| 07:15 | internet cafe | tries again | 0, all of them have left the window | the password is checked again |
Retry-After: 840 means wait 840 seconds, that is 14 minutes, because the 07:00 failures leave the window at 07:15.
In the exercise the methods are named recordFailure(userId, now), isLockedOut(userId, now) and clearFailures(userId), with counting keys like 'u1', and time is a number of milliseconds. The counting key can be any string: in a real app it holds email|ip. The threshold is 5 and the window 15 * 60 * 1000.
Messages that give nothing away
| Situation | The same answer for everyone |
|---|---|
| Forgot password, registered email or not | 200 "If that email is registered, a password reset link is on its way." |
| Failed login, wrong email or wrong password | 401 "Email or password is wrong" |
| Too many failures | 429 "Too many login attempts. Try again in 14 minutes." |
An answer like "Email not registered" tells anyone which emails have a School Portal account. That is why the lockout is counted for unregistered emails as well. If 429 only appeared for accounts that exist, that 429 alone would show that the account exists.
In Laravel
In Laravel, forgot password, the reset and the login pause look like this:
// POST /forgot-password: one answer, whatever the status
Password::sendResetLink($request->only('email'));
return response()->json(['message' => 'If that email is registered, a password reset link is on its way.']);
// POST /reset-password
Password::reset($request->only('email', 'password', 'password_confirmation', 'token'), function (User $user, string $password) {
$user->forceFill(['password' => Hash::make($password)])->setRememberToken(Str::random(60));
$user->save();
DB::table('sessions')->where('user_id', $user->id)->delete(); // every device logs out
$user->notify(new PasswordChanged); // a Notification you write
});
// Login: a pause per email|IP
$key = Str::lower($request->input('email')).'|'.$request->ip();
if (RateLimiter::tooManyAttempts($key, 5)) {
$seconds = RateLimiter::availableIn($key);
throw ValidationException::withMessages(['email' => "Too many login attempts. Try again in {$seconds} seconds."])->status(429);
}
if (! Auth::attempt($request->only('email', 'password'))) {
RateLimiter::hit($key, 15 * 60);
throw ValidationException::withMessages(['email' => 'Email or password is wrong']);
}
RateLimiter::clear($key);
- The example in Laravel's documentation shows the status message from
sendResetLink. For an unregistered email it reads "We can't find a user with that email address." Don't show that message: answer with one message for everyone. - Laravel keeps reset tokens in the
password_reset_tokenstable, one row per email, and itstokencolumn holds a bcrypt hash. It lives 60 minutes (expireinconfig/auth.php), and the row is deleted after a successful reset. setRememberToken(Str::random(60))makes the old "remember me" cookie (the cookie that keeps a user logged in after the browser closes) stop working. Deleting the user's rows insessionslogs every device out, when sessions are kept in a database table (thedatabasesession driver).RateLimiter::hit($key, 15 * 60)starts a 15-minute window at the first failure, and the whole count disappears at once when that window ends. Close to a sliding window, but the failures don't leave one by one.- The reset link is built from the
Hostheader. Laravel's built-inResetPasswordnotification builds its link withurl(), which uses the request'sHostheader. By default Laravel 13 accepts anyHost. So if aPOST /forgot-passwordwith Siti's email arrives withHost: evil.test, Siti receives a real email from School Portal with the linkhttps://evil.test/reset-password/<token>. If Siti clicks it, her token reaches whoever ownsevil.test. Add$middleware->trustHosts()inbootstrap/app.php: any host other than theAPP_URLhost (the Portal's address, set in.env) and its subdomains gets400(not active in thelocalenvironment, the developer's computer). - Response time that leaks.
Password::sendResetLinkmakes every call last at least 200 ms. But for a registered email, Laravel also makes a bcrypt hash of the token and sends the email right away, with no queue, and the two can take longer than 200 ms. So a registered email gets a slower answer. Send the link after the answer is sent:defer(fn () => Password::sendResetLink($request->only('email')));. - The token in the reset page's URL. When the reset page loads something from another site, the browser can send the
Refererheader (the address of the page it came from). Browsers now send only the origin to other sites in theRefererheader, without the rest of the address that holds the token. But OWASP (an organisation that publishes web security guides) still advisesReferrer-Policy: no-referrer(send noRefererat all) on the reset page, as a safeguard.
⚠️ What locks the owner out, or keeps the intruder in
- A permanent lock per account. Five wrong passwords from anyone keep the owner out. Use a temporary pause per
email|IP. - Resetting without revoking sessions. Whoever logged in with the old password stays logged in. Delete every session (and refresh token) of that user.
- A different message or status for an unregistered email, in forgot password and in the lockout alike. Both show which emails have an account.
- A weak recovery shortcut, such as the question "name of your first pet". The answer can often be guessed from social media. Use email, and for accounts with MFA, the recovery codes (backup codes) from the Multi-factor Authentication (MFA) lesson.
TL;DR: Forgot password: the reset link holds a random 32-byte token, the server stores only its SHA-256, it lives 60 minutes, it works once, and the /forgot-password answer is the same for every email. After the reset: hash the new password, revoke every session of the user on every device, and send a notification email. Lockout (holding back logins after too many wrong passwords): don't lock an account permanently, because anyone could lock its owner out. Pause temporarily per email|IP pair with a sliding window (only the failures of the last 15 minutes count). 5 failures in the last 15 minutes means 429 with Retry-After (how many seconds to wait). Old failures leave on their own, and a successful login clears the count. The failed-login message is always the same: "Email or password is wrong". In Laravel: Password::sendResetLink, Password::reset, and RateLimiter::tooManyAttempts, hit, clear.
⚡ Forgot password: prove it through email
Meaning: Account recovery: Siti asks for a reset link, proves she owns the account through her email, then sets a new password. The reset token in that link is single use and short-lived, and the server stores only its hash, exactly like a magic link.
⚡ After the reset: revoke every session
Meaning: Changing the password alone doesn't sign out someone who already logged in with the old one, because their session is still valid. So after the reset, delete every one of Siti's sessions and email the owner, so she finds out right away if someone else did the reset.
⚡ A pause per email and IP, not a permanent lock
Guess first: the server holds back logins after five wrong passwords. From an internet cafe, someone types Siti's password wrong five times. A minute later Siti logs in from home with the right password. Can she get in?
Yes, when the failures are counted per email|IP pair: the internet cafe's failures only hold back the pair of Siti's email and the cafe's IP. With a permanent lock per account, Siti is locked out too, even with the right password.
⚡ A 15-minute sliding window
Write:
function isLockedOut(key, now) {
const recent = (failures.get(key) || []).filter((t) => t > now - WINDOW); // the last 15 minutes
failures.set(key, recent); // old ones are dropped
return recent.length >= THRESHOLD;
}
Meaning: failures records the time of each failure per key, such as an email|ip pair. isLockedOut keeps only the failures of the last 15 minutes (WINDOW), then holds back the login once there are THRESHOLD (5) of them. Old failures leave on their own, so typos spread over a day never reach the limit that holds back the login. A fixed counter (a count that only goes up) never drops old failures.