Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 53 ยท Projects

Project: Build and Harden a Login Flow

Build a login flow in Node.js with slow password hashing, rate limiting, lockout and session tokens, then write tests that try to break it.

Almost every application has a login form, and almost every attack on accounts goes through it: guessing passwords, replaying leaked ones, stealing sessions. A secure login is not one clever trick. It is a handful of small, boring defenses that each close one door.

In this project you build a login flow in Node.js and then try to break it with tests. You will store passwords with a slow salted hash, compare them safely, limit attempts per account and per address, lock accounts temporarily, and issue unguessable session tokens. Everything uses only node:crypto and node:assert, runs on the site's Node runner, and uses an in-memory "database". That is a stand-in: a real service needs a real database, HTTPS, cookies with the right flags, multi-factor authentication and logging. Background lessons: Password Attacks and Defenses, Cryptography Essentials and Authentication, Sessions and Access Control Flaws. Only test login systems you own or are authorized to test.

Layers of a safe login

Slow hash Salted scrypt, never plain text.
Rate limit Slow down guessing.
Lockout Pause targeted accounts.
Sessions Random tokens that expire.
1 / 2

Step 1: Store and check passwords

Never store a password, and never store a fast hash such as SHA-256 of one. If the database leaks, fast hashes let attackers try billions of guesses per second. Use a deliberately slow, salted password hashing function: Argon2id, bcrypt or scrypt. Node ships scrypt, so we use it here. Each password gets its own random salt, so equal passwords produce different records and precomputed tables are useless.

Two details are easy to miss. Compare hashes with timingSafeEqual, which takes the same time no matter where the first difference is. And store the parameters with the hash (here as a prefix), so you can raise the cost later and still verify old records.

Node.js Salted scrypt password storage

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The output shows that two records for the same password differ and that only the right password verifies. A real system would also enforce a sensible password policy (length over complexity rules, and a check against known-breached passwords) and offer MFA.

Step 2: Limit guessing

Attackers do two things: brute force (many passwords against one account) and credential stuffing or password spraying (one or a few passwords across many accounts). Defend against both:

  • A per-account limit slows a targeted attack on one user.
  • A per-address limit slows one machine trying many accounts.
  • A temporary lockout (minutes, with growing delays) stops guessing without handing attackers a way to lock everyone out permanently. A permanent lockout is itself a denial-of-service weapon.
  • Return the same error for "no such user" and "wrong password", and spend the same hashing time in both cases, so attackers cannot discover which usernames exist.

To test time-based logic without waiting, pass the clock in as a function. This is a good habit for all security code that depends on time.

Node.js Rate limiting and lockout with a fake clock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that the locked account rejects even the correct password. That is deliberate while locked, but think about the trade-off: an attacker who knows a username can keep it locked. Real systems soften this with per-address limits, progressive delays, CAPTCHAs after failures and alerts to the account owner. Lockout is a balance between security and availability.

Step 3: Sessions, and tests that try to break it

After a successful login, the server creates a session: a random token the browser sends on later requests. Rules for good session tokens:

  1. Generate them with a cryptographic random generator (randomBytes(32)), never from time, counters or user IDs.
  2. Store only a hash of the token on the server. If the session table leaks, the stored values cannot be replayed.
  3. Give every session an expiry and an idle timeout, and delete it on logout.
  4. Issue a new token at login (never reuse one the client supplied), which defeats session fixation.
  5. In a real web app, send the token in a cookie marked HttpOnly, Secure and SameSite.

Now the key habit of this project: write tests that attack your own code. The test file below checks that guessing is stopped, that error messages do not leak, that a logged-out token is dead, and that expired or invented tokens are rejected.

Node.js Sessions plus attack tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Treat every test here as an attacker's idea turned into a regression check: if a later change breaks lockout or leaks a username, a test goes red before an attacker finds out. Add your own: a test that a session token from before a password change no longer works, and one that a client-chosen session ID is ignored at login.

Beyond this project

A production login also needs: HTTPS everywhere; cookie flags; CSRF protection on the login and logout endpoints (see XSS and CSRF defense); MFA or passkeys; secure password reset (single-use, short-lived, never reveal whether an email exists); logging of failures for detection; and notifications when someone signs in from a new device. Use a well-reviewed framework or identity provider where you can. Writing your own is a great way to learn, and a risky way to ship.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is scrypt better than SHA-256 for storing passwords?

    Password hashes should be slow and salted so a leaked database cannot be cracked cheaply. Fast general hashes are the wrong tool.
  2. 2. Why return the same error for an unknown user and a wrong password?

    User enumeration helps targeted attacks. Same message and similar timing reveal nothing about account existence.
  3. 3. What is the risk of a permanent account lockout after a few failures?

    Use temporary lockouts and per-address limits so the defense cannot be turned into an attack on availability.
  4. 4. Why store a hash of the session token instead of the token?

    A leaked table of raw tokens lets attackers hijack every active session. Hashes of high-entropy tokens cannot be replayed.
  5. 5. Why pass the clock into time-based security code?

    An injectable clock makes expiry and lockout behaviour fast, deterministic and testable.

Summary

  • Hash passwords with a slow salted function (scrypt, bcrypt, Argon2id) and compare in constant time.
  • Limit guessing per account and per address, lock temporarily, and give identical errors for unknown users and wrong passwords.
  • Create session tokens with a cryptographic random generator, store only their hash, expire them, and issue a new one at login.
  • Write tests that attack your own code and keep them as regression checks.
  • A real deployment adds HTTPS, secure cookies, CSRF protection, MFA and monitoring.

Next: Project: Server Hardening Checklist Checker.