The first version of the School Portal login already works. Siti can get in, her report card shows up, no errors. But working doesn't mean safe.
Auth best practices are a checklist, not one new feature: small things you already learned one at a time, and all of them must be right at once. Think of a pilot's pre-flight checklist. The pilot is good, but still ticks every line, because one skipped line is enough for a disaster. In this lesson you audit the first version of School Portal's login with seven checks, fix the ones that fail, then write the password rules for the sign-up form.
The setup we audit
This is the first version of School Portal's login, exactly the data the Lab uses. Each row has a check you can run, not just a feeling that "it's probably fine":
| # | What is checked | First version | Result | Taught in |
|---|---|---|---|---|
| 1 | Passwords hashed slowly, with a salt | md5($password) |
fails | Password Hashing |
| 2 | Session cookie HttpOnly, Secure, SameSite |
sid=...; Path=/; HttpOnly |
fails | Session-based Authentication |
| 3 | A failed login always gets the same answer | "Email not registered" and "Wrong password" | fails | Password Hashing |
| 4 | Login attempts are limited | throttle:5,1 |
passes | Rate Limiting for Authentication |
| 5 | A new session ID after login | session()->regenerate() |
passes | Session-based Authentication |
| 6 | Log out of all devices | deletes only the session in use | fails | Device & Session Management |
| 7 | Secrets outside the repo | .env in .gitignore, env('APP_KEY') |
passes | Environment Variables & Secrets (Security track) |
Three pass, four fail. This lesson doesn't repeat those lessons. What's new here: how to check each row and fix it.
Seven checks, one by one
- Hash. Siti's and Mr. Andi's
passwordcolumns are exactly the same:5d7845ac6ee7cfffafc5fe5f35cf666d. That is the MD5 ofsecret123: fast, no salt, so equal passwords look equal. It passes when the value is bcrypt with cost 12 or more ($2y$12$...) or argon2id, and differs per user. - Cookie. Split the
Set-Cookieheader at each semicolon. It needsHttpOnly,Secure, andSameSite=LaxorStrict. The first version is missing two. - Error message. Send two failed logins: an email that isn't registered, and Siti's email with a wrong password. The status and the message must be the same:
401and "Email or password is wrong". If they differ, the login form becomes a tool for checking which emails are registered. - Rate limit. Send six wrong logins within one minute. With
throttle:5,1, the first five get401and the sixth gets429 Too Many Requestswith aRetry-Afterheader. - Regenerate. Compare the session ID before and after login. They must differ.
- Log out everywhere. Siti is logged in on her laptop, her phone and the school lab computer, so she has three sessions. On the laptop she presses "Log out of all devices". The first version deletes only the laptop's session, so two remain: the phone and the lab computer are still logged in. It passes when none remain.
- Secrets.
.envis listed in.gitignore,git ls-filesdoesn't include.env, and the code readsAPP_KEYthrough config instead of writing it out.
The fixes for the four that fail, in Laravel:
// 1. Hash: bcrypt cost 12 (BCRYPT_ROUNDS=12), not md5
$user->password = Hash::make($request->password);
// 2. Production .env: config/session.php already has http_only true and same_site lax
// SESSION_SECURE_COOKIE=true
// 3. One message for every failed login
if (! Auth::attempt($credentials)) {
return response()->json(['message' => 'Email or password is wrong'], 401);
}
// 6. Log out of all devices (session driver: database)
DB::table('sessions')->where('user_id', $request->user()->id)->delete();
Auth::logout();
$request->session()->invalidate();
Hash::makegives a 60-character string with the salt inside. An old MD5 hash can't be converted directly: on the user's next login, match it once the old way, then store theHash::makeresult (the same idea as rehashing in the Password Hashing lesson).Auth::attemptreturnsfalsefor an unregistered email and a wrong password, so one branch answers both with the same status and message.- The
sessionstable stores each session'suser_id, so onedeleteends every device. Laravel also hasAuth::logoutOtherDevices($password)(it needs theauth.sessionmiddleware).
Rehashing at login replaces only the hashes of users who log in again. The MD5 hashes of users who never come back stay in the database. Other options, from OWASP (Password Storage Cheat Sheet):
| Way | When to pick it |
|---|---|
| Rehash at login (the way above) | for active users. The simplest, and the result is a plain bcrypt hash. |
| Wrap the old hash now | so that no bare MD5 is left in the database from today. Store Hash::make($user->password) in every row and mark the row. At login, check Hash::check(md5($password), ...), then replace it with a plain Hash::make($password), because a wrapped hash is easier to crack. |
| Delete hashes no one uses | for accounts that have not logged in for months: delete the hash and ask for a password reset by email. The safest, but the user must create a new password. |
Rate limit: limiting login attempts
Brute force protection means limiting the number of failed logins, then adding a delay after several failures:
Route::post('/login', [LoginController::class, 'store'])->middleware('throttle:5,1');
throttle:5,1 means 5 attempts per 1 minute, counted per IP. One key alone is not enough. A key of the email plus the IP stops one account being tried again and again from one IP, but the same account can still be tried from 100 other IPs, and one IP can still try 100 other accounts. So set several limits at once: a strict one on email|IP, a looser one per IP, and one per account that asks for a captcha after several failures. The Auth Rate Limiting lesson covers this in detail. After repeated failures the delay can grow longer each time. Locking the account and telling its owner is covered in the Account Recovery & Lockout lesson.
Password rules at sign-up
School Portal's sign-up form rejects a weak password before hashing it. The rules follow the NIST SP 800-63B guidance, and they're also what this lesson's exercise grades: three rules, checked in order, and each failed rule adds one message:
| Order | Rule | Message when it fails |
|---|---|---|
| 1 | length at least 8 | At least 8 characters |
| 2 | length at most 64 | At most 64 characters |
| 3 | not on the breached-password list (compared in lower case) | This password is on the breached list |
const errors = [];
if (password.length < 8) errors.push("At least 8 characters");
if (password.length > 64) errors.push("At most 64 characters");
if (BREACHED_LIST.includes(password.toLowerCase())) errors.push("This password is on the breached list");
return { valid: errors.length === 0, errors };
- Each
ifstands on its own, so one password can get more than one message, in the table's order.errors.join("|")joins them with a|separator. validistruewhenerrorsis empty.- NIST allows a minimum of 8 only for a password used together with a second factor (MFA). When the password is the only factor, NIST requires at least 15.
.lengthin JavaScript counts UTF-16 units, not characters:"🔑".lengthis 2. NIST counts each code point (one Unicode character) as one character, so in a real app count with[...password].length, which is 1 for"🔑".
| Password | valid |
errors |
|---|---|---|
Ab1! |
false |
At least 8 characters |
qwerty |
false |
At least 8 characters|This password is on the breached list |
Password |
false |
This password is on the breached list |
coffee milk palm sugar |
true |
empty |
Mixed-character rules such as "must have an uppercase letter, a digit and a symbol" are left out on purpose. NIST SP 800-63B advises against forcing a mix of character types: people end up writing Password1!, which meets every rule and sits on every breach list. What really helps: put length first (15 characters when the password is the only factor), allow long passwords of at least 64 characters, and reject passwords found on breach lists. The list in the exercise is only a small sample; a real server checks millions of passwords, for example through Have I Been Pwned. In Laravel: Password::min(15)->uncompromised().
If the hash is bcrypt, there is one more limit: bcrypt reads only the first 72 bytes, and ignores the rest without any message. Emoji and non-Latin letters take several bytes per character, so 64 characters can be more than 72 bytes. Refuse passwords over 72 bytes, or use argon2id, which has no such limit. In Laravel, BCRYPT_LIMIT=72 makes Hash::make refuse a longer password, so no hash is cut short without anyone knowing.
Random tokens, not assembled ones
Tokens for login, password reset, or an API must be random. md5($user->id . time()) is assembled: the id is small, time() is just the current second, and MD5 is deterministic and fast, so anyone can compute it again. That token has no expiry either.
$token = bin2hex(random_bytes(32)); // 64 hex characters, 256 random bits
DB::table('api_tokens')->insert([
'user_id' => $user->id,
'token_hash' => hash('sha256', $token), // only its hash is stored
'expires_at' => now()->addMinutes(15),
]);
📌 What the seven checks leave out
The full checklist is longer: MFA for admin accounts (the Multi-factor Authentication lesson), a short access token with a rotated refresh token (Refresh Token Rotation), CSRF for cookie-based forms (CSRF Protection), and a record of every login, failed login, and logout (Audit Logs & Auth Trail).
⚠️ Checks that pass on paper and leak in production
- The same message, but a different status or timing.
401for a wrong password and422for an unregistered email still leaks. The server also still runs one dummy hash for an email that doesn't exist. - The checklist is ticked once, then forgotten.
SESSION_SECURE_COOKIEis left out of the production.env. Make these checks tests that run in CI. env()called outside theconfigfolder. Afterphp artisan config:cache,env('APP_KEY')returnsnull. Read it withconfig('app.key').- Rule messages that aren't exact. In the exercise,
"At least 8 characters"and the others are checked letter by letter, and their order is checked too. - Forcing uppercase letters, digits and symbols. Composition rules push people to write
Password1!, which is on every breach list. Put length and the breach list first.
TL;DR: Secure auth is a checklist where everything passes: bcrypt or argon2id hashes with a salt, HttpOnly; Secure; SameSite cookies, one message for every failed login, throttle on login (429 on the sixth attempt), a new session ID after login, a logout that ends every session, and secrets in a .env that is never committed. Tokens come from random_bytes(32) and only their hash is stored. The exercise's password rules follow NIST SP 800-63B: at least 8 (15 when the password is the only factor), at most 64, refuse passwords on the breach list, one message per failed rule, and no composition rules.
⚡ A checklist, not a new feature
Meaning: Secure auth is small things that must all be right at once, like a pilot's pre-flight checklist: bcrypt or argon2id hashes with a salt, HttpOnly; Secure; SameSite cookies, a new session ID after login, a logout that ends every session, and secrets in a .env that is never committed.
⚡ One message for every failed login
Guess first: an unregistered email gets "Email not registered", a wrong password gets "Wrong password". What's the danger?
The login form becomes a tool for checking which emails are registered. Answer both with the same status and message: 401 and "Email or password is wrong".
Meaning: Auth::attempt returns false in both cases, so one branch answers both.
⚡ Limit login attempts
Write:
Route::post('/login', [LoginController::class, 'store'])->middleware('throttle:5,1');
Meaning: This is brute force protection: 5 attempts per minute. The sixth wrong login gets 429 Too Many Requests with a Retry-After header.
⚡ Length and the breach list, not a character mix
Write:
if (password.length < 8) errors.push("At least 8 characters");
if (password.length > 64) errors.push("At most 64 characters");
if (BREACHED_LIST.includes(password.toLowerCase())) errors.push("This password is on the breached list");
Meaning: Follow NIST SP 800-63B: length comes first, and passwords that have been breached are refused. Don't require uppercase letters, digits and symbols, because people end up writing Password1!, which is on every breach list.