Software Development Guide
Build a Secure Login System:
Sessions, Cookies and Password Reset Explained
Register · Sign In · Protect · Recover
Understand passwords, session cookies, protected requests and recovery by examining one working local application—and verifying its failure cases.
Authentication lab
Browser → Server → DatabaseQuick answer
How do you build a secure login system?
Verify passwords with slow, salted hashes; rotate an unpredictable session ID after login; put server-managed identity behind a restricted cookie; authorise every protected request; and make recovery tokens single-use and time-limited. Confirm the failure cases through reproducible tests.
- Hash
- Rotate
- Authorise
- Recover
- Test
A secure login system must verify a user’s credentials, store passwords as slow salted hashes, create a new server-side session after sign-in, send the session ID in a restricted cookie, and enforce permissions on every protected request . It also needs reliable logout, abuse controls and a single-use password-reset flow. The way to know whether these features work is to test what the server rejects as carefully as what it accepts.
In this guide, we will follow one small Node.js + SQLite learning project—from registration through password recovery—and inspect the requests and database records that make it work. The examples use fictional accounts such as mira@example.test ; do not enter real credentials or records in this local demonstration. [1] [2] [5] [7]
What you will finish with: a clear model of cookies versus sessions, a working localhost practice application, and repeatable checks for authentication, authorisation and recovery failures. The companion practice project is supplied separately for editors and students; the public download should be added only after its permanent link is verified.
A login form is not the entire security system
Think of a shared personal-notes application with two fictional members, Mira and Joel. They each have a valid account and password. After signing in, Mira must be able to open her private note, but Joel must not gain access by guessing its numeric ID. That is the difference between recognising an account and permitting a particular action.
- Authentication verifies the claimed account, for example by checking a password.
- Session management lets the server recognise a browser on later requests, subject to expiry and revocation.
- Authorisation checks what the signed-in account may read or change. A successful login is not permission to access every record.
- Account recovery restores access without letting a stolen or guessed recovery link become a new login route.
The browser displays forms and carries requests, but it must not decide whether a student owns a confidential record. That check belongs on the backend. Passwords also never belong in page URLs, ordinary application logs or browser localStorage . The underlying requirements are set out in OWASP’s authentication and session guidance. [1] [2]
Decide what an attacker must not be able to do
A useful security plan starts with concrete failure cases rather than abstract promises. In our fictional notes application, imagine somebody who does not know Mira’s password, somebody who knows Joel’s password but wants Mira’s notes, and somebody who found an old password-reset link. These are three different problems; one login check cannot solve all of them.
| Attempt | Control and observable result |
|---|---|
| Guess Mira’s password repeatedly | Slow salted password verification plus monitored, proportionate throttling; repeated attempts are limited. |
| Copy an old anonymous session ID and wait for Mira to log in | Session ID regeneration after successful login; the previous ID cannot access Mira’s account. |
| Sign in as Joel, then change the requested note ID to Mira’s | Backend ownership check using the authenticated session’s user ID; the other person’s note is not returned. |
| Reuse an old reset link | Server checks expiry and single-use status; replay fails. |
| Submit an unwanted cross-origin update | Application-specific CSRF and Origin checks reject the request. |
| Steal an unexpired cookie | This remains a serious risk; HttpOnly helps against direct JavaScript cookie reads but does not eliminate XSS, malware or session theft. |
On a phone, swipe the table sideways to view both columns.
This is a small threat model : a list of assets, plausible misuse and testable protections. It also reveals the article’s most important distinction: authentication identifies Joel, but authorisation must still prevent him from accessing Mira’s information. [1] [2] [6] [10]
Cookies and sessions: follow one real request
HTTP requests are independent: the server does not automatically remember that a person signed in earlier. In a server-managed session design, a cookie lets the browser carry an unpredictable session identifier. The corresponding authenticated state stays on the server. [2] [3]
- Before login: Mira opens the site. The app may create an anonymous session and issue a CSRF token.
- Sign in: The browser submits the credentials. The server looks up the account and verifies its password against a slow salted hash.
- Rotate: On success, the server invalidates the previous session ID, creates a new one and associates it with Mira’s account.
- Remember: The server returns a Set-Cookie header. The browser sends that cookie on eligible later requests.
- Authorise: The server finds the session record, checks its expiry, and applies the relevant permission or ownership rule before returning data.
- End: Logout, expiry or a password reset makes old server-side session records unusable.
Look at the two sides of the exchange:
| Browser holds | Backend holds and checks |
|---|---|
| An opaque, unpredictable session ID in an HTTP cookie | A session record linked to a user ID, with expiry and revocation rules |
| Cookie rules including HttpOnly and SameSite | Password hashes, account records and access decisions |
| A short-lived CSRF token used for state-changing requests in this lab | A verifier for that CSRF token, tied to the session |
| A reset token only while completing a local recovery flow | A hash of the reset token and its expiry, until consumed |
On a phone, swipe the table sideways to view both columns.
Do not confuse the cookie with the session. Clearing the cookie in a browser only removes the local reference. The server must also invalidate the record so a copied old identifier will no longer work. A session-based design is a good learning choice, although other architectures—including tokens signed and carried by clients—exist. [2] [3]
Prepare the Node.js authentication project
The companion lab uses Node.js built-in HTTP and cryptography modules plus a SQLite database. Unlike a typical Express tutorial, this demonstration deliberately exposes the session logic so you can trace it. It is not a template for public deployment ; production projects should use reviewed authentication and session libraries. You need Node.js 22.13 or later , a terminal, and sufficient memory for the sample scrypt configuration. The SQLite interface in Node 22 is experimental.
Project structure (once you extract the companion lab ZIP):
Open a terminal inside the extracted folder containing package.json . Run these commands in order:
No package installation from npm is needed for this particular lab. The tests use a separate disposable database, so the test suite will not erase practice accounts in the normal lab database.
Follow one complete workflow: register mira@example.test with a new practice-only password of 15–128 characters; sign in; click Check protected endpoint ; sign out; then request a reset using the same fictional address. The server prints a local-only recovery link to the terminal. Paste it into your own browser, choose a different practice password and try using the link twice. The second attempt should fail.
What the browser will call:
| Endpoint | Expected purpose |
|---|---|
| GET /api/csrf | Create or refresh an anonymous/authenticated CSRF token |
| POST /api/register | Validate and create a practice account |
| POST /api/login | Check credentials and issue a new authenticated session |
| GET /api/me | Return the current account only when signed in |
| POST /api/notes | Create a private practice note for the authenticated account |
| GET /api/notes/:id | Return the practice note only if the authenticated account owns it |
| POST /api/logout | Revoke the current session and expire its cookie |
| POST /api/forgot | Start recovery using a generic public response |
| POST /api/reset | Validate and consume a one-use reset token |
On a phone, swipe the table sideways to view both columns.
The lab binds to 127.0.0.1 and uses plain HTTP exclusively for local learning. Never expose it to the public internet or use real student, customer or financial data. An actual HTTPS site must use Secure cookies and further deployment controls. [2] [3]
Understand the four database tables before writing a route
Many beginners understand the login form but cannot explain how login stays valid. The lab uses four SQLite tables to make that answer visible:
| Table | What is stored (and what is deliberately excluded) |
|---|---|
| users | Account ID, email, salted password hash, creation time; never plaintext passwords |
| sessions | Hashed random session ID, user ID, CSRF-token verifier, activity and expiry times; never the reusable raw session ID |
| reset_tokens | Hashed single-use recovery token, associated user ID and expiration time; never the raw reset token |
| practice_notes | Note ID, note text and the account ID of the owner; ownership is enforced in the server-side query |
On a phone, swipe the table sideways to view both columns.
The data flow is POST /api/login → verify stored password hash → create a random session ID → store only its hash with the associated user ID → send the raw opaque ID in a cookie. On a subsequent request, the server hashes the cookie ID and looks up the matching session. That lets the server revoke the record without placing account details inside the cookie.
Teaching distinction: Passwords use deliberately slow, salted scrypt ; random session IDs and reset tokens are already high-entropy secrets, so the lab stores their SHA-256 digests for database lookup. Do not use fast SHA-256 as a replacement for password hashing. [2] [5]
Step 1 — Register a user without storing plaintext passwords
A registration endpoint should accept only the data it needs, validate it server-side, and save a password hash rather than the password itself. In the lab, the users table records a numeric ID, normalised email, password hash and creation time. The browser never decides what an account is authorised to do.
The practice application uses a 15–128-Unicode-code-point password rule and a deliberately tiny illustrative blocklist. These are demonstration settings, not a complete leaked-password screening system. NIST SP 800-63B-4 (July 2025) requires at least 15 characters for a single-factor password, recommends permitting at least 64, and counts each Unicode code point as one character. It discourages composition tricks and routine forced changes, and supports password managers and pasting. A real service should check proposed passwords against a maintained list of commonly used or compromised values. [4]
A subtle JavaScript bug to avoid: somePassword.length counts UTF-16 code units, not Unicode code points. For example, eight lock emojis contain 16 JavaScript code units but only eight Unicode code points. A naive length >= 15 check could incorrectly accept them. The companion lab was corrected to use […value].length for this particular length rule:
This counts Unicode code points rather than what a person visually perceives as grapheme clusters; it is the counting distinction in NIST’s verifier guidance. The server is the policy authority: HTML field length validation may use UTF-16-based measurements and must not replace it. [4]
Try it: Register Mira, then try the same email twice. The registration handler uses the same generic response text instead of a revealing “account already exists” message; timing and other side channels still require assessment in a public application. Use a SQLite viewer on the local learning-lab.sqlite file while the application is stopped, and inspect the users table: password_hash must contain a derived value, not the practice password. Account verification and real confirmation email delivery are deliberately outside this demo. Avoid opening or editing the live database while it is being written.
Step 2 — Hash passwords using a slow, salted algorithm
A hash is a one-way derived value. When a user signs in, the application derives a value from the submitted password and compares it with the stored reference. Do not store plaintext passwords and do not use ordinary SHA-256 as a password hashing algorithm.
This project uses Node’s memory-hard scrypt , a fresh 16-byte salt per password and explicit work settings ( N=2^17 , r=8 , p=1 ). These match an OWASP-listed scrypt configuration. OWASP generally prefers Argon2id for new applications when it is available; tune password-hash cost against the service’s hardware and abuse limits. [5]
A random salt means the same password will generally produce a different stored result for each account. The lab applies Unicode NFC normalisation before deriving the hash and before verifying it. This follows NIST’s recommendation for accepted Unicode passwords and prevents otherwise equivalent composed and decomposed spellings from producing different derived values. The server then compares the resulting fixed-length hash bytes with timingSafeEqual ; this does not eliminate all application-level timing differences. [4] [5]
The salt is not a secret; the stored hashes still require careful database access, backups and an upgrade strategy when hashing parameters change. scrypt with the shown configuration uses substantial memory by design, making concurrent guessing more expensive but also making uncontrolled signup and verification traffic a capacity risk. Production services need resource-aware throttling and load tests, not simply a stronger hash setting. The revised tests verify both canonical Unicode equivalence and that the old password fails after a reset.
Step 3 — Verify login and replace the old session ID
A browser may have an anonymous session before signing in. The server must not simply attach the new user ID to an identifier that might already be known to someone else. A successful login should replace the old session ID; this is the key defence against session fixation . [2]
The lab checks the account, validates the password hash, returns a generic 401 for invalid credentials and applies a small demonstration rate limit. For unknown users it performs a dummy password-hash comparison to reduce an obvious timing signal, although equal response timing is not guaranteed. The relevant success path is:
Verify it in the browser: use a wrong password (expect 401 ), then the correct one (expect 200 ). In DevTools → Application/Storage → Cookies, compare the session ID before and after sign-in; the value must change. Inspect it privately without copying it into screenshots or messages.
Why limit login attempts? Without abuse controls, repeated guessing is possible. The lab’s small Map -based, per-address limiter is an observable teaching example only: it resets when the process restarts, is not shared across multiple servers, and can itself be used to block legitimate sign-in attempts. Real services need shared, risk-aware throttling, monitoring, resource limits and breach-password screening. Registration and recovery also need abuse protection. [1]
How the example creates a session
This is the corresponding simplified excerpt from server.mjs . newToken() generates 32 random bytes; hash() computes a SHA-256 digest. The database stores hash(id) , while the browser receives the opaque id in its cookie.
To inspect it, open the local SQLite database while the app is stopped. The session row contains a digest rather than the raw cookie value. That is not permission to share either value: both account databases and browser sessions are security-sensitive.
Step 4 — Configure and understand session cookies
A cookie is an HTTP mechanism for carrying small values between a browser and server. In this tutorial it carries the session ID. Cookie restrictions affect where that ID can travel and which browser interfaces can access it. The following is an illustrative HTTPS deployment configuration , not the exact local HTTP cookie from the lab.
| Cookie setting | Why it matters |
|---|---|
| Secure | Restricts the cookie to HTTPS requests (with browser-specific localhost exceptions). |
| HttpOnly | Prevents ordinary client-side JavaScript from reading the cookie through document.cookie. |
| SameSite=Lax | Restricts many cross-site requests; not a complete CSRF defence. |
| Path=/ | Makes the cookie available for the intended site-wide path. |
| No Domain | Keeps the cookie host-only rather than sharing it across subdomains. |
| __Host- prefix | Requires Secure, Path=/ and no Domain in supporting browsers. |
On a phone, swipe the table sideways to view both columns.
Important: Setting Secure on an application that you are serving over ordinary remote HTTP can prevent the cookie from being sent. The lab uses a different non-production cookie name and an HTTP localhost connection. Any actual public deployment needs correctly configured HTTPS, a Secure cookie and carefully evaluated proxy trust settings. MDN documents the Set-Cookie attributes and host-only prefixes [3] .
Read the actual local header: nit_learning_sid=<opaque-id>; Path=/; HttpOnly; SameSite=Lax . Unlike the illustrative HTTPS response above, this lab header does not use a __Host- prefix or a Secure attribute. In Chrome DevTools, compare that distinction directly. On a real HTTPS site, configure the host-only __Host- pattern where appropriate and validate that the deployed reverse proxy reports a trusted secure connection. [3] [8]
Browser cookie expiry is not the same as server expiry
The sample database enforces an idle limit of 20 minutes and an absolute limit of eight hours . These are examples for the practice application, not mandatory values for every site. A user active every few minutes may extend the idle timer, but cannot extend the absolute limit. Expiry decisions happen server-side; even if an old browser cookie remains, its expired session must be rejected. A production design should select timeouts according to the risks of its users and data. [2]
Step 5 — Protect API routes and state-changing requests
A hidden dashboard button is not an access control. The backend must check the session for each protected endpoint and then check what that user is permitted to see. For example, viewing Mira’s private note must use the authenticated identity and a server-side ownership rule, not a note ID sent by an untrusted page.
The local lab demonstrates that its protected account endpoint returns a denial before login and succeeds after login. It also checks a synchroniser-style CSRF token on state-changing requests and verifies their Origin. Real applications must adapt the defensive checks to their architecture and protect against XSS as well.
Prove that two different users cannot access each other’s records
The revised companion lab now includes a minimal practice_notes table, POST /api/notes to create a note, and GET /api/notes/:id to read one. Only a signed-in user may create a note, and the server ignores any attempted owner_user_id in the request body . The owner comes from the authenticated session. The note lookup includes the authenticated account ID directly in its database query:
The revised npm test sequence does something more rigorous than checking whether /api/me returns success. First Mira signs in and creates a note. Then Joel signs in successfully and requests Mira’s exact note ID . The server returns 404 because the note does not belong to Joel, even though Joel’s login is valid. After signing back in as Mira, the test confirms that she can read her own note but not Joel’s. An anonymous request returns 401 . These are distinct expected results: 401 identifies missing authentication, while a privacy-preserving 404 here avoids disclosing the existence of another account’s record. [10]
This experiment demonstrates object-level authorisation without creating a full multi-user management system. Run npm test and read the assertions in tests.mjs ; change the ownership predicate deliberately in a disposable local copy only if you are studying how the negative test detects a mistake. Never disable ownership checks in a real application. OWASP recommends validating permissions on every request and creating regression tests for that logic. [10]
How to interpret the three most useful denial statuses
| HTTP response | What it means in this practice project |
|---|---|
| 401 Unauthorized | No valid authenticated session accompanies a protected request. Despite its name, this status concerns authentication. |
| 403 Forbidden | The server rejects a state-changing request that fails the demo’s Origin or CSRF checks. |
| 404 Not Found | A private note is absent or belongs to another account; the response does not confirm that the other person’s note exists. |
On a phone, swipe the table sideways to view both columns.
The number alone cannot prove security: inspect which account made the request, which backend rule executed and what information the response contains. [10]
What prevents CSRF and session fixation?
Cross-site request forgery (CSRF) occurs when an attacker induces a browser to submit an unwanted action using credentials that the browser automatically attaches. For cookie-based sessions, a state-changing request should carry a server-validated protection such as an appropriate CSRF token, along with origin checks and other controls suited to the application.
A session fixation weakness occurs when an attacker can cause the victim to authenticate using a session identifier that the attacker already knows or can influence. Issuing a fresh identifier after login reduces this risk.
In this project, the browser first fetches a CSRF token from /api/csrf , then sends it in X-CSRF-Token for POST requests. The server also checks Origin . The token verifier is tied to the current server-side session. One lab-specific behaviour matters: each fresh request to /api/csrf replaces the earlier token for that session. With two tabs open, the token in one tab may become stale and yield a 403 ; refresh that tab’s token rather than disabling CSRF validation.
A CSRF token and SameSite=Lax address different parts of the problem. Neither prevents XSS, so the application must still treat user-controlled output safely and limit script capabilities. For public systems, prefer reviewed framework support and test all allowed origins and cross-origin configurations. [6]
Step 6 — Make logout actually end the session
A visual Sign out button is insufficient if the server continues accepting the old session. Proper logout invalidates the server-side record and sends a response telling the browser to expire its cookie. The next protected request using the previous identifier must be denied.
Follow this sequence in DevTools: sign in, successfully request the protected endpoint, sign out, then request the protected endpoint again. The last request should fail. Closing a tab or browser is not a reliable replacement for server-side session expiration because mobile browsers and sessions may behave differently [2] .
Step 7 — Build a password-reset process that does not reveal accounts
Password recovery is a separate security-sensitive workflow. The service must let legitimate users regain access without allowing attackers to guess accounts, forge recovery links or keep using an old session after a password change.
1. Request
User enters their address. Always return a generic message such as “If that account exists, recovery instructions will be sent.”
2. Create
Generate an unpredictable random reset token, store a hash of it with an expiration time and associate it with one user.
3. Deliver
Send the reset link through an appropriate private channel. The localhost lab prints the link to its terminal for demonstration only.
4. Consume
Verify expiry and single-use status, store the newly hashed password, revoke old sessions and do not log the user in automatically.
The lab’s token lasts 15 minutes , is stored as a hash, and is consumed at most once within a database transaction. This duration is a design choice, not a universal standard. The reset link contains the token in a URL fragment ( #token=… ), which a browser does not send in the initial HTTP request. The revised local page reads the token into temporary JavaScript memory, immediately removes the fragment from the visible address using history.replaceState , and then submits it in the reset request. The token is still sensitive while in page memory; this approach is not a substitute for removing untrusted scripts and using HTTPS. The application deletes the user’s old sessions when the password changes, and it does not silently log them back in. [7]
Exercise: request a recovery link for a practice address, copy the local-only link from your terminal, choose a new practice password, and try the same link twice. The second use must fail. Then try the old password: it must also fail.
A recovery link is a sensitive credential
Never include a reset token in analytics, third-party scripts, routine application logs or screenshots. Build recovery URLs from a trusted configured origin, use HTTPS for actual delivery, and set a restrictive Referrer-Policy. A successful reset should not silently sign in the user. See OWASP Forgot Password guidance [7] .
Step 8 — Run the acceptance tests before trusting the feature
Successful login is only one test. You must also prove that incorrect credentials, missing sessions, invalid recovery tokens and cross-origin requests are denied. The companion project includes an automated Node.js integration test you can run with the following command.
The expanded companion project integration test was run on 16 November 2026 with Node.js 22.16.0 and passed. It checks the behaviours listed below; it does not claim to cover every possible security scenario. Run it again on your own computer after changing the code. The suite starts a separate server with a temporary SQLite database, then removes its test data.
| What to test | Expected result |
|---|---|
| Register a fictional account | User record saved with a salted password hash. |
| Submit a too-short Unicode password | HTTP 400; eight supplementary characters must not be mistaken for 16 code points. |
| Sign in with canonically equivalent Unicode password forms | Succeeds after consistent NFC normalisation. |
| Request protected data before login | HTTP 401: no authorised session. |
| Request Mira’s note while signed in as Joel | HTTP 404: another user’s record remains unavailable. |
| Supply a fake owner ID while creating Joel’s note | Server uses Joel’s authenticated session as the owner. |
| Enter wrong password | HTTP 401 with a generic failure response. |
| Sign in correctly | Authenticated session; session ID rotated. |
| Sign out | Former session no longer authorises requests. |
| Submit without CSRF token | HTTP 403; action rejected. |
| Reuse a previous CSRF token after /api/csrf rotation | HTTP 403; an outdated token is rejected in this lab. |
| Submit from the wrong origin | HTTP 403; action rejected. |
| Request recovery for unknown address | Same public message as for an existing address. |
| Use incorrect or reused reset token | Password change rejected. |
| Reset password correctly | Old password and existing sessions invalidated. |
| Expire the session in the database | Old session denied even if browser has cookie. |
On a phone, swipe the table sideways to view both columns.
Inspect the evidence yourself
Open the application in your browser and launch DevTools → Network . Clear the log, sign in and select the /api/login request. Check that the response is 200 and a new Set-Cookie header was issued. Then open Application/Storage → Cookies to see HttpOnly and SameSite=Lax . The local HTTP cookie deliberately does not carry Secure ; do not mistake that for a recommendation for public sites.
Next click Sign out , then Check protected endpoint . You should see 401 or the equivalent not-signed-in outcome, even if you manually retain a previous cookie. Finally, test missing CSRF tokens, expired/reset-used links and an invalid origin using the automated suite. On narrow screens, check the app’s labels, buttons and keyboard focus—not just whether the page happens to fit. Never share raw cookie IDs or recovery URLs.
Why does a login system fail? A debugging map
Use evidence from the browser’s Network panel, the application’s own development logs and database state. Do not repeatedly change security settings until a failed login “starts working” without understanding what changed.
| Symptom | What to check first |
|---|---|
| Login succeeds but next page says signed out | Was the cookie set, retained and returned? Check SameSite, domain, path and HTTPS mode. |
| Cookie disappears in deployment | Check Secure and the actual HTTPS/proxy configuration. |
| 403 on a legitimate form | Confirm that a second tab has not rotated the lab’s CSRF token; re-fetch /api/csrf and check Origin . |
| User sees another user’s data | Inspect the server-side authorisation rule, never merely the frontend visibility. |
| Valid login but missing notes | Check whether the note belongs to the signed-in account; do not treat a 404 as proof of missing authentication. |
| Reset link immediately fails | Check that the entire #token= fragment was copied, that the token is unused, and that the database expiry has not passed. |
| Reset works but old device remains signed in | Confirm all relevant server-side sessions were revoked. |
| Password appears in logs | Remove credential logging and investigate whether logs or telemetry need protection. |
On a phone, swipe the table sideways to view both columns.
Do not “fix” cookies by disabling security
If a Secure cookie fails under local HTTP, use the intentional local-only configuration. For public traffic, restore HTTPS and Secure cookie settings, then test the proxy and origin correctly. Turning off CSRF or HttpOnly to silence an error hides the underlying defect.
Where would you use the same authentication design?
The general architecture applies to many different applications, but each also needs its own authorisation rules:
- School portal: Mira signs in to view her results. Only her own results may be returned, while authorised teachers have different permissions.
- Salon appointment system: A stylist signs in to see permitted bookings. A customer cannot access another customer’s private appointment history.
- Plant-equipment maintenance app: A technician records work done on a machine. Only permitted supervisors can approve certain changes.
- Online shop administration: A shop owner manages stock and orders; ordinary buyers must not be able to use administrative endpoints.
The login mechanism identifies the account. It does not replace application-specific roles, permissions, ownership rules, audit trails or transaction controls. Design those rules before connecting confidential records.
Is the example ready for production?
No. The local project demonstrates the required moving parts and has automated acceptance checks, but a real login service requires additional design, infrastructure, monitoring and independent security validation. Do not deploy the provided raw HTTP teaching server for public users.
Transport and cookies
HTTPS, HSTS, Secure cookies, correct reverse-proxy trust and reliable production session storage.
Account protection
MFA or passkeys where appropriate, real compromised-password screening, risk-aware rate limiting and secure email verification.
Recovery and operations
Reliable email delivery, audit logs that avoid secrets, abuse monitoring, backup protection and incident procedures.
Review and testing
Maintained dependencies, framework security updates, CSRF/XSS assessment, authorisation tests and independent security review.
The project deliberately uses Node’s built-in HTTP server to make authentication logic visible, and its attempt limiter is an in-memory teaching control. Real applications should normally build upon a maintained authentication framework and session library rather than hand-writing every security primitive. The Express session documentation warns that its default MemoryStore is not designed for production [8] .
What does “secure enough” mean?
It depends on the application, its data, its threat model and its operational environment. Passing the included local checks confirms selected behaviours; it cannot certify the complete system against every attack.
Frequently asked questions about login, cookies and sessions
What is the difference between a cookie and a session?
A cookie is a browser mechanism that carries a small value with eligible HTTP requests. In this server-side design, the cookie carries an opaque ID; a server-side session record stores the authenticated state and expiry controls.
Is a password hash the same as encryption?
No. Encryption is reversible with an appropriate key. Password hashing uses a one-way, deliberately expensive process with a unique salt so the verifier can check a password without storing it in plaintext.
Should I store login tokens in localStorage?
For this cookie-session design, no. An appropriately restricted HttpOnly cookie helps prevent JavaScript from directly reading the session identifier. You still need XSS prevention and CSRF defences.
Are HttpOnly, Secure and SameSite enough to stop every attack?
No. They reduce specific risks. They do not replace server-side authorisation, CSRF validation, XSS prevention, TLS configuration, secure recovery, logging discipline or monitoring.
Does every login system need JWT?
No. Many web applications work well with server-managed sessions and cookies. JWTs may suit some architectures but introduce their own storage, expiry, validation and revocation considerations.
Does clicking Logout remove every browser and device session?
Not necessarily. A normal logout may revoke only the current session. An explicit “sign out all devices” action or password-recovery policy should revoke other sessions when required.
Why do password-reset tokens expire?
Expiry reduces the window during which a captured recovery link could be used. Tokens must also be unpredictable and single-use; expiration alone is insufficient.
Can I publish the teaching application to a live website?
Do not publish this particular demo. It runs under deliberate localhost restrictions and lacks a complete production security, deployment and operations programme.
Technical references and further reading
- OWASP — Authentication Cheat Sheet . Authentication errors, rate controls and reauthentication.
- OWASP — Session Management Cheat Sheet . Session identifiers, rotation and expiry.
- MDN — Set-Cookie Header . Cookie attributes and prefixes.
- NIST — SP 800-63B . Current password verifier and authentication guidance.
- OWASP — Password Storage Cheat Sheet . Argon2id, scrypt, salts and hashing trade-offs.
- OWASP — CSRF Prevention Cheat Sheet . CSRF tokens and request validation.
- OWASP — Forgot Password Cheat Sheet . Single-use reset tokens and account privacy.
- Express — Session Middleware Documentation . Production storage and cookie settings.
- Newton Institute of Technology — Full-Stack Software Development Course . Verified course details and admissions route.
- OWASP — Authorization Cheat Sheet . Deny-by-default, per-request permissions and regression testing.
Sources reviewed 16 November 2026. Educational guidance may need revision as official recommendations and libraries change.
Learn full-stack development at Newton Institute of Technology
Practical ICT training
Building authentication connects HTML forms, browser networking, backend logic, databases, access control and software testing. NIT’s Full-Stack Software Development programme includes practical work across these areas. The currently published pathway is 8 months of institutional training , followed by at least 3 months of industrial attachment . Refer to the official course page for current programme terms and admissions.
Prepared by: Newton Institute of Technology Editorial Team. Technical exercises were checked with Node.js 22.16.0; institutional expert review and public hosting verification remain separate publication requirements.
Newton Institute of Technology · Migori Town, Kenya · For Kenya, Africa and the world.