Neha, a freelance developer in Amritsar, is building a student portal for a small coaching institute: students log in to see their batch timings, test marks and fee receipts. The deadline is close, so she creates a users table with an email column and a password column, and saves whatever the student types, exactly as typed. "Just for now," she tells herself, "I'll secure it before launch." Two weeks later the institute hires an intern to build attendance reports, and the owner hands him a copy of last night's database backup. Neha opens the file to check something and sees every one of the 300 students' passwords in plain text, sitting in a dump that is now on someone else's laptop. Several of those passwords are clearly the same ones the students use for their email.
Nothing was "hacked", yet every account is exposed. So what should a login system store, and how does the server know who is calling an API after the student logs in? This post answers both: the difference between authentication and authorization, sessions and tokens, how JWTs really work (and what they do not protect), and how bcrypt stores passwords so that a leaked backup gives away much less. Along the way we build one small Express app with registration, login, a protected /me route and an admin-only route, and test it to show the real 200, 401 and 403 responses.
Authentication vs Authorization
These two words sound alike and are often shortened to "auth", but they answer different questions. Authentication answers "who are you?": the system checks that you really are the user you claim to be, for example by checking your password. Authorization answers "what are you allowed to do?": once the system knows who you are, it checks whether this particular user may read this page, delete this record or see this report. Authentication always comes first, because you cannot check someone's permissions before you know who they are.
A coaching institute building makes the difference easy to see. The guard at the gate checks your ID card: that is authentication. Inside, a student's card opens the classrooms and the library, but not the accounts office or the staff room: that is authorization. Being let in through the gate does not mean every door opens. A hotel room key works the same way: reception verifies you once at check-in, and the key then opens your room and the gym, but not another guest's room.
A related point that beginners mix up is login versus authentication. Login is the user's action (typing an email and password and pressing a button). Authentication is the server's work behind it: finding the user, checking the password, confirming the account is active, and then issuing something the client can use to prove its identity on later requests.
401 vs 403: The Status Codes That Tell Them Apart
HTTP has one status code for each kind of failure, and using the right one helps the front end react correctly. Confusingly, 401 is named "Unauthorized" even though it really means "unauthenticated".
| Code | Meaning in plain words | Typical cause | What the client should do |
|---|---|---|---|
401 Unauthorized | "We don't know who you are." | No token, an expired token, a tampered token, wrong password at login | Refresh the token or send the user to the login page |
403 Forbidden | "We know who you are, but you can't do this." | A student calling an admin route, a teacher editing another teacher's course | Show "you don't have access"; logging in again will not help |
An easy memory trick: 401 means "not logged in", 403 means "logged in, but no permission". Strictly, the HTTP standard also says a 401 response should include a WWW-Authenticate header naming the scheme (such as Bearer); many JSON APIs skip it, but it is good to know when an interviewer asks. Some APIs return 404 instead of 403 for other users' private resources, so that an attacker cannot even learn that the record exists.
Authentication Factors and MFA
Security people group ways of proving identity into three factors. Each one has a different weakness, which is why combining them works so well.
| Factor | Examples | Main weakness |
|---|---|---|
| Something you know | Password, PIN, security question | Can be guessed, phished, reused across sites or leaked in a breach |
| Something you have | Phone receiving an OTP, authenticator app, hardware security key, ATM card | Can be lost or stolen; SMS OTPs can be intercepted through SIM swap fraud |
| Something you are | Fingerprint, face recognition | Cannot be changed if copied; usually unlocks a key on the device rather than being sent to the server |
You already use these every day. An ATM asks for your card (have) and PIN (know). Your phone unlocks with a PIN or fingerprint. A UPI payment needs the phone with your registered SIM (have) and your UPI PIN (know).
Multi-factor authentication (MFA) means the user must pass checks from at least two different factors. A password plus a one-time password (OTP) sent to the phone is the most common example: the user types the password, the server verifies it, then asks for a six-digit OTP. A password plus a security question is not MFA, because both are "something you know" and both can be leaked together. MFA matters because passwords leak all the time. If an attacker gets a student's password from another website's breach, they still cannot log in without the phone. OTP codes from an authenticator app are generally preferred over SMS, because they cannot be redirected by a SIM swap.
A sensible rule is that the stronger the account's powers, the stronger the login. For the coaching portal, students and parents might use email plus password (or an OTP-only login on mobile), while teachers and especially admins, who can change marks and see fee records, should be required to use MFA. Other common methods include social login ("Sign in with Google"), where another provider authenticates the user and your server trusts its signed answer, and passkeys, where the device holds a private key unlocked by fingerprint or face.
Session-Based vs Token-Based Authentication
HTTP is stateless: each request arrives on its own, and the server does not automatically remember that this browser logged in a minute ago. After a successful login, the server must hand the client something to send with every later request, so that the user does not type the password on every click. There are two main designs.
Sessions: The Hotel Wristband
At a resort, reception checks your ID once and gives you a wristband; staff look you up by the wristband after that. In session-based authentication, the server checks the password, creates a session record such as { sessionId: "k8Qv...", userId: 1001 } in memory, a database or Redis, and sends only the random sessionId to the browser in a cookie. The browser sends the cookie automatically with each request, and the server looks up the session to find the user. Because the server keeps this record, the approach is called stateful.
The original version of this post said sessions are hard to scale because every server must know every session. That is the concern, but it has a standard fix: keep sessions in a shared store such as Redis that all servers read. The real costs are one store lookup per request and one more piece of infrastructure to run.
Tokens: The Airport Boarding Pass
At an airport, your identity is checked once and you receive a boarding pass. Later checkpoints read the pass itself; they do not phone the check-in counter. In token-based authentication, the server checks the password and returns a signed token that contains the user's ID and role. The client sends it on every request, usually in a header: Authorization: Bearer <token>. Any server that knows the signing key can check the signature and trust the contents without looking anything up, which is why tokens are called stateless. JSON Web Tokens (JWTs) are the most common format.
| Session (cookie with session ID) | Token (JWT) | |
|---|---|---|
| What the client holds | A random ID with no meaning by itself | The user's claims (ID, role, expiry) plus a signature |
| Where the truth lives | Server-side store (memory, database, Redis) | Inside the token; the server only needs the key |
| Cost per request | One store lookup | One signature check (CPU only) |
| Logout and revocation | Easy: delete the session record | Hard: a valid token works until it expires, unless you add a block-list |
| Multiple servers | Need a shared store such as Redis | Any server with the key can verify |
| Typical fit | Server-rendered websites, one main web app | APIs used by mobile apps and other services, many back-end services |
| Main risk | CSRF if cookies are not SameSite | Theft from localStorage via XSS; long-lived tokens that cannot be revoked |
The Login Flow, Step by Step
Whatever you choose, a token login with a password follows the same sequence. The diagram below shows the client, the API server and the database, with each step numbered.
- The user submits credentials. The front end sends
POST /loginwith the email and password in a JSON body, always over HTTPS. - The server looks up the user by email (normalised to lower case) in the database.
- The database returns the user row, including the stored password hash, the role and flags such as "account active".
- The server checks the password with
bcrypt.compare(). If it matches and the account is active, it creates a JWT withjwt.sign(). - The server responds with
200and the token, or401with one generic message ("Invalid email or password") whether the email or the password was wrong. - The client sends the token on later requests in the
Authorization: Bearer ...header. - Middleware verifies the token on every protected route: no token or a bad token gives
401, a valid token without the right role gives403, and otherwise the controller runs.
Steps 1 to 5 happen once per login; steps 6 and 7 happen on every API call. That split is the whole point of a token: the slow, sensitive work (the password check) happens rarely, and the frequent work (the signature check) is fast.
Building It in Express: Register, Login, /me and an Admin Route
Here is one small, complete app for the coaching portal, using Express 5, jsonwebtoken and bcrypt. Users live in an in-memory array so the example runs without a database; in a real app those lines become database queries. If you are new to routing and middleware, the Express.js Complete Guide explains app.use, next() and the request lifecycle first.
npm init -y
npm install express jsonwebtoken bcrypt
# installed: express@5.3.0, jsonwebtoken@9.0.3, bcrypt@6.0.0
bcrypt is a native add-on. Version 6 ships prebuilt binaries, and it installed and ran on Windows with Node.js v24 for this post without any build tools. If the install ever fails on your machine (usually with a node-gyp error), use npm install bcryptjs and require('bcryptjs') instead. It is pure JavaScript with the same hash, compare and getRounds API, only somewhat slower.Setup and the Secret Key
The JWT signing secret is the most important value in the app: anyone who has it can create a token that says role: "admin". So it is read from an environment variable and the app refuses to start without it. Never paste a secret into your code, and never commit it to Git.
// app.js
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const JWT_SECRET = process.env.JWT_SECRET; // never hard-code this
if (!JWT_SECRET) throw new Error('Set the JWT_SECRET environment variable');
const BCRYPT_COST = 12;
const PORT = 3140;
// In-memory "database": resets on restart (a real app uses MySQL, MongoDB etc.)
const users = []; // { id, email, passwordHash, role }
const courses = [
{ id: 1, title: 'Class 12 Physics', teacherId: 2 },
{ id: 2, title: 'NEET Biology', teacherId: 3 },
];
let nextId = 1;
// Tiny demo blocklist; a real app checks a large breached-password list
const COMMON_PASSWORDS = new Set(['123456789012345', 'password1234567', 'qwertyuiopasdfg']);
async function createUser(email, password, role) {
const passwordHash = await bcrypt.hash(password, BCRYPT_COST);
const user = { id: nextId++, email, passwordHash, role };
users.push(user);
return user;
}
const app = express();
app.use(express.json({ limit: '10kb' }));
Running node app.js without the variable stops immediately with Error: Set the JWT_SECRET environment variable, which is far better than silently signing tokens with undefined. For local work, put JWT_SECRET=... in a .env file (listed in .gitignore) and start the app with node --env-file=.env app.js. A good secret is long and random, for example the output of node -e "console.log(require('crypto').randomBytes(32).toString('hex'))", not a word like secret123.
Registration
app.post('/register', async (req, res) => {
const { email, password } = req.body ?? {};
if (typeof email !== 'string' || !email.includes('@')) {
return res.status(400).json({ error: 'A valid email is required' });
}
// Length rules from NIST SP 800-63B; 72 bytes is bcrypt's input limit
if (typeof password !== 'string' || password.length < 15) {
return res.status(400).json({ error: 'Password must be at least 15 characters' });
}
if (Buffer.byteLength(password) > 72) {
return res.status(400).json({ error: 'Password is too long' });
}
if (COMMON_PASSWORDS.has(password.toLowerCase())) {
return res.status(400).json({ error: 'This password is too common. Choose another.' });
}
const normalised = email.trim().toLowerCase();
if (users.some((u) => u.email === normalised)) {
return res.status(409).json({ error: 'Email already registered' });
}
// role is NEVER read from req.body: every new account is a student
const user = await createUser(normalised, password, 'student');
res.status(201).json({ id: user.id, email: user.email, role: user.role });
});
Three details matter here. The password is hashed with bcrypt before it is stored, and the plain text is never saved or logged. The role is set by the server, not copied from the request; if you write createUser(email, password, req.body.role), anyone can register as an admin by adding "role": "admin" to the JSON (this kind of bug is called mass assignment). And the response never includes passwordHash. The length and blocklist rules follow current NIST guidance, explained in the password policy section below. Note that req.body ?? {} is there because in Express 5, req.body is undefined when no body was parsed.
Login
// A real hash, so an unknown email takes as long to reject as a wrong password
const DUMMY_HASH = bcrypt.hashSync('not-a-real-password', BCRYPT_COST);
app.post('/login', async (req, res) => {
const { email, password } = req.body ?? {};
const user = users.find((u) => u.email === String(email).trim().toLowerCase());
const ok = await bcrypt.compare(String(password), user ? user.passwordHash : DUMMY_HASH);
if (!user || !ok) {
return res.status(401).json({ error: 'Invalid email or password' }); // same message for both
}
const accessToken = jwt.sign({ role: user.role }, JWT_SECRET, {
subject: String(user.id),
expiresIn: '15m',
algorithm: 'HS256',
});
res.json({ accessToken });
});
The login answers with the same message and the same status whether the email does not exist or the password is wrong. If it said "no such email", an attacker could use the login form to find out which emails are registered. The DUMMY_HASH trick closes a quieter version of the same leak: without it, an unknown email would be rejected almost instantly while a known one waits for bcrypt (around 300 ms at cost 12 on the test machine), and that timing difference alone reveals which accounts exist. The token stores the user ID in the standard sub (subject) claim and expires in 15 minutes.
The Authentication Middleware: Who Are You?
function authenticate(req, res, next) {
const [scheme, token] = (req.get('authorization') || '').split(' ');
if (scheme !== 'Bearer' || !token) {
return res.status(401).json({ error: 'Login required' });
}
try {
const payload = jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'] });
req.user = { id: Number(payload.sub), role: payload.role };
next();
} catch (err) {
const msg = err.name === 'TokenExpiredError' ? 'Token expired' : 'Invalid token';
return res.status(401).json({ error: msg });
}
}
Middleware acts like the security guard at the gate: it runs before the route handler, and if the check fails, the request stops there with a 401 and the controller never runs. Compare it with the version in the original post, which had two bugs. It passed the whole header, "Bearer eyJ...", to jwt.verify, which fails with JsonWebTokenError: invalid token because of the "Bearer " prefix. And it verified the token but threw the result away, so later code had no idea which user was calling. Here the decoded user is attached to req.user for the next handlers. Pinning algorithms: ['HS256'] means the server accepts only the algorithm it actually uses.
The Authorization Middleware: What May You Do?
function requireRole(...allowed) {
return (req, res, next) => {
if (!allowed.includes(req.user.role)) {
return res.status(403).json({ error: 'You do not have permission for this' });
}
next();
};
}
requireRole is a function that returns middleware, so one helper covers every role check: requireRole('admin'), requireRole('teacher', 'admin'), and so on. That is better than writing a separate authorizeVendor, authorizeAdmin and authorizeTeacher function for each role, as the original did, because the rule lives in one place. It must always run after authenticate, since it reads req.user.
The Routes
app.get('/me', authenticate, (req, res) => {
const user = users.find((u) => u.id === req.user.id);
if (!user) return res.status(401).json({ error: 'Account no longer exists' });
res.json({ id: user.id, email: user.email, role: user.role }); // never send passwordHash
});
app.get('/admin/users', authenticate, requireRole('admin'), (req, res) => {
res.json(users.map(({ id, email, role }) => ({ id, email, role })));
});
// Resource-based: a teacher may edit only their OWN course
app.patch('/courses/:id', authenticate, requireRole('teacher', 'admin'), (req, res) => {
const course = courses.find((c) => c.id === Number(req.params.id));
if (!course) return res.status(404).json({ error: 'Course not found' });
if (req.user.role !== 'admin' && course.teacherId !== req.user.id) {
return res.status(403).json({ error: 'You can only edit your own courses' });
}
if (typeof req.body?.title === 'string') course.title = req.body.title;
res.json(course);
});
module.exports = { app, createUser, PORT };
Read each route from left to right: path, then the checks in order, then the handler. /me needs only a valid login. /admin/users needs a login and the admin role. PATCH /courses/:id needs the teacher or admin role, and then a third check inside the handler: does this teacher own this course? That last check cannot be done by role alone, which is the subject of the next section. Public routes, such as a course catalogue, simply leave out authenticate.
Testing It End to End
This test script seeds an admin and two teachers (in a real app you would create staff accounts with a one-time admin script, never through a public sign-up), starts the server on port 3140, calls every route with fetch, and closes the server. Run it with JWT_SECRET=dev-only-secret-change-me node test.js (on PowerShell, set $env:JWT_SECRET first, or use --env-file).
// test.js
const { app, createUser, PORT } = require('./app');
(async () => {
await createUser('admin@institute.example', 'admin-pass-for-testing-only', 'admin'); // id 1
await createUser('ravi@institute.example', 'teacher-pass-ravi-123', 'teacher'); // id 2
await createUser('simran@institute.example', 'teacher-pass-simran-1', 'teacher'); // id 3
const server = app.listen(PORT, async () => {
const base = `http://localhost:${PORT}`;
async function call(method, path, { body, token } = {}) {
const headers = {};
if (body) headers['Content-Type'] = 'application/json';
if (token) headers.Authorization = `Bearer ${token}`;
const res = await fetch(base + path, { method, headers, body: body && JSON.stringify(body) });
const data = await res.json();
console.log(method, path, '->', res.status, JSON.stringify(data));
return data;
}
await call('POST', '/register', { body: { email: 'aman@student.example', password: 'short' } });
// POST /register -> 400 {"error":"Password must be at least 15 characters"}
await call('POST', '/register', { body: { email: 'aman@student.example', password: 'password1234567' } });
// POST /register -> 400 {"error":"This password is too common. Choose another."}
await call('POST', '/register', { body: { email: 'aman@student.example', password: 'golden temple at 6 am', role: 'admin' } });
// POST /register -> 201 {"id":4,"email":"aman@student.example","role":"student"} (role: 'admin' ignored)
await call('POST', '/register', { body: { email: 'Aman@student.example', password: 'another one 12345' } });
// POST /register -> 409 {"error":"Email already registered"}
await call('POST', '/login', { body: { email: 'aman@student.example', password: 'wrong password' } });
// POST /login -> 401 {"error":"Invalid email or password"}
await call('POST', '/login', { body: { email: 'nobody@student.example', password: 'whatever123' } });
// POST /login -> 401 {"error":"Invalid email or password"}
const { accessToken: student } = await call('POST', '/login', { body: { email: 'aman@student.example', password: 'golden temple at 6 am' } });
// POST /login -> 200 {"accessToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoic3R1ZGVudCIs...EUQ_nPmuRLM9uDaZ3rgRQHcbEODTjaNnTFChmysmiJ4"}
await call('GET', '/me');
// GET /me -> 401 {"error":"Login required"}
await call('GET', '/me', { token: student });
// GET /me -> 200 {"id":4,"email":"aman@student.example","role":"student"}
await call('GET', '/me', { token: student.slice(0, -2) + 'xx' });
// GET /me -> 401 {"error":"Invalid token"}
await call('GET', '/admin/users', { token: student });
// GET /admin/users -> 403 {"error":"You do not have permission for this"}
const { accessToken: admin } = await call('POST', '/login', { body: { email: 'admin@institute.example', password: 'admin-pass-for-testing-only' } });
await call('GET', '/admin/users', { token: admin });
// GET /admin/users -> 200 [{"id":1,"email":"admin@institute.example","role":"admin"},{"id":2,...},{"id":3,...},{"id":4,"email":"aman@student.example","role":"student"}]
const { accessToken: ravi } = await call('POST', '/login', { body: { email: 'ravi@institute.example', password: 'teacher-pass-ravi-123' } });
await call('PATCH', '/courses/1', { token: ravi, body: { title: 'Class 12 Physics (2027 batch)' } });
// PATCH /courses/1 -> 200 {"id":1,"title":"Class 12 Physics (2027 batch)","teacherId":2}
await call('PATCH', '/courses/2', { token: ravi, body: { title: 'Hacked' } });
// PATCH /courses/2 -> 403 {"error":"You can only edit your own courses"}
await call('PATCH', '/courses/1', { token: student, body: { title: 'Hacked' } });
// PATCH /courses/1 -> 403 {"error":"You do not have permission for this"}
server.close(() => console.log('Server closed')); // Server closed
});
})();
Every rule shows up in the output. No token gives 401, a token with two characters changed gives 401, a valid student token on an admin route gives 403, and the same route with an admin token gives 200. The sneaky "role": "admin" in the registration body was ignored, and Ravi could edit his own course but got 403 on Simran's. (The token and hash values change on every run because they include the current time and a random salt.)
Authorization in Depth: Roles, Ownership and Least Privilege
Roles and Permissions (RBAC)
A permission is one specific action, such as "upload test marks" or "view fee reports". A role is a named bundle of permissions, such as "teacher". In role-based access control (RBAC), you give permissions to roles and roles to users, instead of giving permissions to each user one by one. An institute with 300 students, 12 teachers and two office staff has only four or five roles to manage, and when a new teacher joins you assign one role instead of ticking twenty boxes.
| Role | Can | Cannot |
|---|---|---|
| Student | View own marks, own attendance, own fee receipts; download course notes | See other students' data, upload marks, change fees |
| Teacher | Upload marks and notes for own batches; view attendance of own batches | Edit other teachers' courses, see fee records, manage users |
| Accounts staff | Record fee payments, issue receipts, view fee reports | Change marks or course content |
| Admin | Manage users and roles, view all reports | (Everything is allowed, which is exactly why admin logins need MFA) |
In a database this is usually three small tables: users (each with a role_id), roles, and role_permissions (which permissions each role has). For a small app, a role column checked with requireRole() is enough. As the app grows, checking permissions instead of role names, for example requirePermission('marks:upload'), avoids if (role === 'admin' || role === 'teacher' || ...) scattered across the code, which was one of the mistakes listed in the original post.
Resource-Based Authorization: "Is This Yours?"
Roles answer "can teachers edit courses?" but not "can this teacher edit this course?". Ravi and Simran are both teachers, yet Ravi must not be able to change Simran's NEET Biology notes. On an online marketplace the same rule appears as "a vendor may edit only their own products", and on a bank app as "a customer may see only their own accounts". This is resource-based (or ownership) authorization: load the record, compare its owner with req.user.id, and return 403 if they differ, exactly as the PATCH /courses/:id route does.
Missing ownership checks are one of the most common API security bugs. It is listed in the OWASP API Security Top 10 as "Broken Object Level Authorization". The pattern is always the same: GET /fees/receipts/1043 works for the student who owns receipt 1043, and the developer forgets that any logged-in student can also try 1042 and 1044. A safe habit is to include the owner in the query itself, such as WHERE id = ? AND student_id = ?, so another user's record is never even loaded. A full product update in a real system therefore goes through several layers: authenticate the token, check the role, check ownership, then run the controller.
Why Authorization Must Be Server-Side
Hiding the "Delete" button for non-admins in React is good user experience, but it is not security. Anyone can open the browser's developer tools, or skip the browser entirely and call your API with curl or Postman, sending any method to any URL. The front end can decide what to show; only the back end can decide what is allowed. Every permission check that matters must run on the server, on every request, even if the front end already checked.
The Principle of Least Privilege
Give every user, and every piece of software, only the permissions it actually needs, and nothing more. Students do not need "delete course", so the student role should not have it, even if no button exposes it. The same rule applies beyond users: the database account your API uses should not be allowed to drop tables, and the intern building attendance reports should get read-only access to attendance data, not a full backup with the users table in it. When something does go wrong, least privilege limits how much damage one stolen password or one bug can do.
JWT Explained: What Is Inside the Token
A JSON Web Token (JWT), defined in RFC 7519, is a compact string with three parts separated by dots: header.payload.signature. Here is the student token from the test above, split into its parts:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 <- header
.eyJyb2xlIjoic3R1ZGVudCIsImlhdCI6MTc5MzYwODU4NCwiZXhwIjoxNzkzNjA5NDg0LCJzdWIiOiI0In0 <- payload
.EUQ_nPmuRLM9uDaZ3rgRQHcbEODTjaNnTFChmysmiJ4 <- signature
| Part | What it contains | Decoded example |
|---|---|---|
| Header | The signing algorithm and the token type | {"alg":"HS256","typ":"JWT"} |
| Payload | The claims: statements about the user and the token | {"role":"student","iat":1793608584,"exp":1793609484,"sub":"4"} |
| Signature | HMAC-SHA256 of header.payload, computed with the server's secret | 32 raw bytes; not readable text |
Claims: sub, iat, exp and Your Own
A few claim names are registered in the standard, and libraries understand them. sub (subject) is who the token is about, usually the user ID as a string. iat (issued at) and exp (expires) are times in seconds since 1 January 1970, not milliseconds: 1793609484 - 1793608584 = 900, which is the 15 minutes we asked for. iss (issuer) and aud (audience) say who created the token and who it is for, which matters when several services share keys. Anything else, such as role, is a custom claim.
Keep the payload small: an ID, a role, and the standard times. Do not store the email, phone number, fee status or anything that changes often. The token travels with every request, and data inside it can be out of date for as long as the token lives.
Base64url Is Encoding, Not Encryption
The header and payload are only base64url-encoded: JSON converted to letters, digits, - and _ so it can travel safely in a URL or header. Encoding is reversible by anyone, without any key. Encryption needs a key to reverse. So the payload of a normal JWT is readable by anyone who sees the token, including browser extensions, proxies, logs and the user themself.
{"role":"student","iat":1793608584,"exp":1793609484,"sub":"4"} in plain text. The browser console gives the same result without any website: atob('eyJyb2xlIjoic3R1ZGVudCIs...'). She had planned to add each student's phone number and fee balance to the token "to save a database call". She drops that idea: the signature stops anyone from changing the payload, but it does nothing to stop anyone from reading it.const jwt = require('jsonwebtoken');
const secret = process.env.JWT_SECRET;
const token = jwt.sign({ sub: '42', role: 'student', name: 'Aman' }, secret, { expiresIn: '15m' });
const [h, p, s] = token.split('.');
console.log(token.split('.').length); // 3
console.log(Buffer.from(h, 'base64url').toString()); // {"alg":"HS256","typ":"JWT"}
console.log(Buffer.from(p, 'base64url').toString());
// {"sub":"42","role":"student","name":"Aman","iat":1793608430,"exp":1793609330}
console.log(jwt.decode(token).role); // student (decode does NOT check the signature)
const v = jwt.verify(token, secret);
console.log(v.exp - v.iat); // 900
Notice the difference between jwt.decode() and jwt.verify(). decode just reads the payload and accepts any token, even a forged one. It is fine for showing a name in the UI, but never use it to make a security decision. Always use verify on the server.
Signing and Verifying: Why Tampering Fails
The signature is calculated from the header, the payload and the secret. If anyone changes even one character of the payload, the signature no longer matches, and only someone with the secret can produce a new valid one. Think of a stamped and signed certificate: you can read it, but if you change the marks, the signature gives the change away. Here are the failures you will see from jsonwebtoken:
// 1. Change "student" to "admin" in the payload, keep the old signature
const fake = Buffer.from(JSON.stringify({ ...JSON.parse(Buffer.from(p, 'base64url')), role: 'admin' }))
.toString('base64url');
jwt.verify(`${h}.${fake}.${s}`, secret); // JsonWebTokenError: invalid signature
// 2. Verify with a different secret
jwt.verify(token, 'some-other-secret'); // JsonWebTokenError: invalid signature
// 3. A token whose exp is in the past
const old = jwt.sign({ sub: '42', exp: Math.floor(Date.now() / 1000) - 60 }, secret);
jwt.verify(old, secret); // TokenExpiredError: jwt expired
// 4. The "alg": "none" trick: no signature at all
const none = Buffer.from('{"alg":"none","typ":"JWT"}').toString('base64url') + '.' + fake + '.';
jwt.verify(none, secret); // JsonWebTokenError: jwt signature is required
// 5. Not a JWT
jwt.verify('abc', secret); // JsonWebTokenError: jwt malformed
Case 4 is a famous attack: some early JWT libraries accepted "alg": "none" and skipped the signature check entirely. Current jsonwebtoken rejects it when you pass a secret, and passing algorithms: ['HS256'] to verify, as our middleware does, makes the rule explicit. Case 3 is why TokenExpiredError is worth handling separately: the front end can quietly refresh the token instead of showing an error.
HS256 uses one shared secret both to sign and to verify, which is fine when one back end does both. When many services need to verify tokens, RS256 or ES256 is a better fit: a private key signs, and the services verify with a public key that cannot create tokens.
Token Expiry: Access Tokens and Refresh Tokens
A token that never expires is like a hotel key card that keeps working after checkout: if it is ever stolen, the thief has access for ever. So access tokens are short-lived, typically 5 to 60 minutes. But logging in every 15 minutes would annoy everyone. The usual answer is a pair of tokens:
| Access token | Refresh token | |
|---|---|---|
| Purpose | Call the API | Get a new access token |
| Lifetime | Short: 5 to 60 minutes | Long: days or weeks |
| Sent | On every API request | Only to one refresh endpoint |
| Format | Usually a JWT, verified without a lookup | Often a random string stored (hashed) in the database |
| Can be revoked? | Not easily; you wait for it to expire | Yes: delete it from the database |
The flow is like extending a hotel stay at reception instead of checking out and in again: (1) login returns both tokens; (2) the client uses the access token until the API returns 401 Token expired; (3) the client sends the refresh token to POST /auth/refresh; (4) the server checks it against the database, issues a new access token and a new refresh token, and deletes the old refresh token (called rotation); (5) the client retries the original request. On logout, the server deletes the refresh token, so the session cannot be extended any more.
const crypto = require('crypto');
const refreshStore = new Map(); // sha256(refreshToken) -> { userId, role, expiresAt }; a DB table in real apps
function issueTokens(res, user) {
const accessToken = jwt.sign({ role: user.role }, JWT_SECRET, {
subject: String(user.id), expiresIn: '15m',
});
const refreshToken = crypto.randomBytes(32).toString('base64url'); // random, not a JWT
const key = crypto.createHash('sha256').update(refreshToken).digest('hex');
refreshStore.set(key, { userId: user.id, role: user.role, expiresAt: Date.now() + 7 * 864e5 });
res.cookie('refresh', refreshToken, {
httpOnly: true, // JavaScript in the page cannot read it
secure: true, // sent only over HTTPS (browsers treat localhost as secure)
sameSite: 'strict', // not sent on requests started by other sites
path: '/auth', // sent only to /auth/* routes
maxAge: 7 * 864e5, // 7 days, in milliseconds
});
return accessToken;
}
app.post('/auth/refresh', (req, res) => {
const token = readCookie(req, 'refresh'); // small helper that reads the Cookie header
const key = token && crypto.createHash('sha256').update(token).digest('hex');
const entry = key && refreshStore.get(key);
if (!entry || entry.expiresAt < Date.now()) {
return res.status(401).json({ error: 'Please log in again' });
}
refreshStore.delete(key); // rotation: each refresh token works only once
res.json({ accessToken: issueTokens(res, { id: entry.userId, role: entry.role }) });
});
// Tested with fetch on port 3140:
// Set-Cookie: refresh=<random>; Max-Age=604800; Path=/auth; Expires=Mon, 09 Nov 2026 08:35:36 GMT; HttpOnly; Secure; SameSite=Strict
// refresh with cookie 1 -> 200 [ 'accessToken' ]
// reuse cookie 1 -> 401 {"error":"Please log in again"}
// logout -> 204
// refresh after logout -> 401 {"error":"Please log in again"}
The refresh token is stored as a SHA-256 hash, for the same reason passwords are hashed: if the database leaks, the stored values cannot be used directly. (A fast hash is fine here because the token is 32 random bytes and cannot be guessed; passwords are short and guessable, which is why they need the slow bcrypt.) Rotation means a stolen refresh token that has already been used is worthless, as the "reuse cookie 1" line shows. Many systems go one step further: if an old refresh token is ever presented again, they treat it as theft and revoke all of that user's tokens.
Where Should the Browser Store Tokens?
This is one of the most debated questions in web security, and there is no option without trade-offs:
| Storage | Risk | Protection |
|---|---|---|
localStorage | Any JavaScript on the page can read it, so one XSS bug (or one compromised npm package or analytics script) can steal the token and use it from anywhere | Prevent XSS; keep tokens short-lived. Simple, but the weakest option for long-lived tokens |
httpOnly cookie | Page JavaScript cannot read it. The browser sends it automatically, which opens the door to CSRF (another site triggering requests with the user's cookie) | SameSite=Strict or Lax, Secure, a narrow Path, and CSRF tokens for older browsers or cross-site setups |
| Memory (a JavaScript variable) | Lost on page reload; still readable by XSS while the page is open | Pair with a refresh token in an httpOnly cookie to get a new access token after reload |
A common, balanced design for browser apps is the one used above: the short-lived access token stays in memory and is sent in the Authorization header, and the refresh token lives in an httpOnly, Secure, SameSite=Strict cookie limited to /auth. Mobile apps should use the platform's secure storage (Keychain on iOS, Keystore-backed storage on Android) rather than plain preferences.
The Revocation Problem
Because the server does not look anything up when it verifies a JWT, it also cannot "cancel" one. If an admin removes a teacher at 11:00, that teacher's access token still works until it expires; if the token said role: "admin" and you demote the user, the old token still says admin. Logging out on the client only deletes the client's copy. The practical answers are: keep access tokens short (15 minutes means at most 15 minutes of stale access), revoke the refresh token so it cannot be extended, and for high-risk cases keep a small deny-list of token IDs (the jti claim) or a per-user "tokens valid after" timestamp that the middleware checks. Notice that the last option brings back a lookup per request, which is the very thing JWTs were meant to avoid. That is the honest trade-off.
JWT vs Sessions: Which Should You Use?
The original post's table said JWT is "mobile friendly" and sessions are "web friendly", and that "modern APIs commonly prefer JWT". That is roughly true in practice, but the reasons matter more than the fashion.
| Question | Lean towards sessions | Lean towards JWT |
|---|---|---|
| Who are the clients? | Mainly one website on your own domain | Mobile apps, third-party clients, many front ends |
| How many back ends verify the user? | One app, or a few behind a shared Redis | Many services that should not all query one session store |
| How fast must access be removed? | Immediately (banking, admin panels) | A few minutes of delay is acceptable |
| Team experience | Framework session middleware is mature and simple | Comfortable with expiry, refresh, rotation and storage decisions |
"Stateless" is not free: the moment you add refresh tokens in a database and a deny-list, you have state again. For a single Express app with a React front end on the same domain, sessions in Redis are simpler and easier to revoke. For an API used by an Android app and a separate web app, or split across services, short-lived JWTs plus rotating refresh tokens are a good fit.
Password Hashing with bcrypt
Why Plain-Text Passwords Are So Dangerous
Go back to Neha's backup. A database copy can end up in many places: a backup file, an intern's laptop, a staging server, a support ticket, a misconfigured cloud bucket. If passwords are stored as typed, every one of those copies hands over every account instantly, with zero effort. Worse, people reuse passwords, so a student's portal password is often also their email or Instagram password. Storing passwords in plain text puts accounts on other websites at risk too. Encrypting them is not enough either, as the next table shows.
Hashing vs Encryption
| Hashing | Encryption | |
|---|---|---|
| Direction | One-way: password to hash is easy, hash to password is not possible directly | Two-way: anyone with the key can decrypt |
| Key | No key (a salt, which is not secret, is stored with the hash) | A secret key that must be protected |
| Output size | Fixed length, whatever the input | Grows with the input |
| Use for | Passwords: you only need to check them, never read them | Data you must read back: Aadhaar or PAN numbers, bank details, documents |
| Analogy | A paper shredder: you can tell whether two papers shred the same way, but cannot rebuild one | A locked box: whoever has the key can open it |
If passwords were encrypted, the key would have to sit on the same server that uses it. An attacker who gets the database usually gets the key too, and then has every password. The server never needs the original password back; it only needs to check whether a typed password matches. That is exactly what hashing gives.
Why a Fast Hash Like SHA-256 Is Not Enough
const crypto = require('crypto');
console.log(crypto.createHash('sha256').update('123456').digest('hex'));
// 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
console.log(crypto.createHash('sha256').update('123456').digest('hex'));
// 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92 (identical every time)
// Speed on the test machine: 1,00,000 SHA-256 hashes took about 343 ms
Two problems are visible. First, the same password always gives the same hash, so attackers can prepare a huge table of common passwords and their hashes in advance (a rainbow table is a space-saving version of this lookup table) and simply look up each leaked hash. Every user with 123456 also shares one hash, so cracking one cracks them all. Second, SHA-256 is designed to be fast. One laptop CPU managed about 3 lakh guesses per second in this test, and graphics cards are far faster. Speed is good for checking file downloads and terrible for password storage.
Salt: Making Every Hash Unique
A salt is a random value generated for each password and mixed in before hashing. It is not secret; it is stored right next to the hash. Because each user's salt is different, two users with the same password get different hashes, a precomputed rainbow table is useless (it would have to be rebuilt for every salt), and an attacker must attack each account separately. bcrypt creates the salt for you and stores it inside the hash string, which is why you never handle it yourself.
bcrypt: Salted and Deliberately Slow
bcrypt is a password-hashing algorithm (published in 1999 and based on the Blowfish cipher), and the bcrypt npm package is one implementation of it. It adds a salt automatically and has a cost factor that makes it slow on purpose. Hashing the same password twice shows both features:
const bcrypt = require('bcrypt');
const pw = 'chai-at-golden-temple-6am';
const a = await bcrypt.hash(pw, 12);
const b = await bcrypt.hash(pw, 12);
console.log(a); // $2b$12$J8p/lMI.X3LdGYUjlnQ2XuhoxKYxEnTEGA5AVX1gXDVayadeJx0ku
console.log(b); // $2b$12$SCnT6fEMyXyJdNJWW9tCseNp4bOSBJEDJEqXQfzJBoWHGNHZqvA9i
console.log(a === b, a.length); // false 60
console.log(await bcrypt.compare(pw, a)); // true
console.log(await bcrypt.compare(pw, b)); // true
console.log(await bcrypt.compare('wrong', a)); // false
console.log(pw === a); // false (never compare strings directly)
console.log(bcrypt.getRounds(a)); // 12
Each 60-character hash is self-describing: $2b$ is the bcrypt version, 12$ is the cost, the next 22 characters are the salt, and the last 31 are the hash itself. That is why compare needs only the typed password and the stored string. A correction to the original post: during login, bcrypt does not create a "new hash" and compare it with the old one. It reads the salt and cost from the stored hash, hashes the typed password with that same salt and cost, and checks whether the results are equal. A plain password === hash can never work, because one is the password and the other is a hash.
The Cost Factor (Not "Salt Rounds")
The number passed to bcrypt.hash(password, 12) is often called "salt rounds", including in the original post, but it is really a cost factor (work factor): bcrypt does 2cost rounds of key setup. Each +1 doubles the time, as these runs on the test machine show:
for (const cost of [10, 12, 14]) {
const t = performance.now();
await bcrypt.hash(pw, cost);
console.log(cost, Math.round(performance.now() - t), 'ms');
}
// 10 75 ms
// 12 296 ms
// 14 1227 ms (timings from one test machine; yours will differ)
A legitimate user logs in once and does not notice 300 ms. An attacker with a stolen hash table must pay that cost for every single guess on every single account. OWASP's Password Storage Cheat Sheet says to use a work factor of at least 10 for bcrypt. A practical approach is to pick the highest cost that keeps login under roughly a quarter to half a second on your production server; 12 is a common choice today. Because the cost is stored in each hash, you can raise it later: after a successful login, check bcrypt.getRounds(hash) and re-hash with the new cost if it is lower.
bcrypt's 72-Byte Limit
bcrypt only uses the first 72 bytes of the input and silently ignores the rest:
const long = 'a'.repeat(72);
const h = await bcrypt.hash(long, 10);
console.log(await bcrypt.compare(long + 'EXTRA', h)); // true (everything after byte 72 is ignored)
console.log(Buffer.byteLength('पासवर्ड')); // 21 (7 characters, but 21 bytes in UTF-8)
That is bytes, not characters: a Hindi or Punjabi character takes 3 bytes in UTF-8, so a long passphrase in Gurmukhi reaches the limit much sooner than one in English. Our registration route rejects passwords over 72 bytes instead of truncating silently. OWASP notes this limit and recommends Argon2id as the first choice for new systems (available in Node.js through packages such as argon2); bcrypt with a work factor of 10 or more remains acceptable and is still the most widely used option in Node.js projects.
The Registration and Login Lifecycle
| Registration | Login |
|---|---|
| 1. Receive the email and password over HTTPS | 1. Receive the email and password over HTTPS |
| 2. Validate: length, blocklist, valid email, not already registered | 2. Look up the user by email (or use the dummy hash if not found) |
3. bcrypt.hash(password, 12) | 3. bcrypt.compare(password, storedHash) |
| 4. Store only the hash, with a server-chosen role | 4. No match: 401 with a generic message, and count the failure |
5. Return 201 without the hash; the plain password is discarded and never logged | 5. Match: issue the access token (and refresh token), return 200 |
Common Password Attacks and How to Slow Them Down
| Attack | How it works | Main defences |
|---|---|---|
| Brute force | Try every combination: 000000, 000001, ... until one works | Longer minimum length; rate limiting; slow hashing for offline attacks |
| Dictionary attack | Try a list of common passwords and words: 123456, password, qwerty, india@123 | Block common and breached passwords at registration; rate limiting |
| Credential stuffing | Take email-password pairs leaked from another website and try them on yours, betting on reuse | MFA; breached-password checks; rate limiting by IP and by account; alerts on unusual logins |
| Rainbow tables | Look up stolen unsalted hashes in a precomputed table of hash-to-password pairs | Unique salt per password (bcrypt and Argon2 do this automatically) |
It helps to separate online attacks (guessing through your login API) from offline attacks (guessing against a stolen hash file at the attacker's own speed). Rate limiting, temporary lockouts and MFA defend against online attacks. Slow, salted hashing defends against offline attacks, by turning millions of guesses per second into a few per second per core. You need both. The Node.js Backend Architecture post shows how to add rate limiting, such as a cap on login attempts per minute, with Redis.
A Password Policy That Actually Helps (Corrected)
The original post recommended "minimum 8 characters, uppercase, lowercase, number and special character required". That was standard advice years ago, but current guidance from NIST (the US National Institute of Standards and Technology) in SP 800-63B says otherwise, because composition rules push people towards predictable patterns like Password@123, which attackers try early. A modern policy is short:
- Favour length. NIST SP 800-63B-4 requires at least 15 characters when the password is the only factor, and allows a minimum of 8 when it is used together with MFA. Accept at least 64 characters, so people can use passphrases like
golden temple at 6 am(remembering bcrypt's 72-byte limit). - Check against breached and common passwords. Reject passwords found on a blocklist of commonly used or previously leaked passwords, and tell the user why.
- No forced composition rules. Do not demand a mix of uppercase, digits and symbols; allow all printable characters, spaces and Unicode.
- No periodic rotation. Do not force a password change every 90 days; require a change only when there is evidence the password was compromised.
- Help the user. Allow paste and password managers, and offer an option to show the password while typing.
Interview Questions, Checked and Corrected
These are the questions from the original post with answers short enough to say aloud. Where the original answer was incomplete or slightly wrong, the stronger version is given.
1. What is authentication, and why does it matter? Authentication verifies that a user is who they claim to be, for example by checking a password, an OTP or a passkey. Without it, anyone could read or change any data, and no action could be traced to a person.
2. What is the difference between authentication and authorization? Authentication asks "who are you?"; authorization asks "what may you do?". Authentication comes first. A failed authentication returns 401, a failed authorization returns 403.
3. What is MFA? Multi-factor authentication requires proof from at least two different factor types: something you know, have or are. Password plus OTP is MFA; password plus security question is not, because both are "know".
4. What is authorization, and why must it be enforced on the back end? Authorization decides which actions a user may perform. Front-end checks only hide buttons; anyone can call the API directly with curl or Postman, so every check that matters must run on the server, on every request.
5. What is RBAC? What does it miss? Role-based access control gives permissions to roles and roles to users. It does not answer ownership questions ("is this your order?"), so you also need resource-based checks, and missing those is a top API vulnerability.
6. What status code is returned for authorization failures? 403 Forbidden. Some APIs return 404 for other users' private resources to avoid revealing that they exist. Not-logged-in is 401.
7. What is a JWT, and what are its three parts? A JSON Web Token is a signed, compact token carrying claims: header.payload.signature. The header names the algorithm, the payload holds claims such as sub, role, iat and exp, and the signature proves the first two were not changed. The original called it "a secure way to transmit user information"; more precisely it is tamper-proof but not secret.
8. Should sensitive data be stored in a JWT payload? No. The payload is base64url-encoded, which anyone can decode without a key. Only put identifiers and roles there. (Encrypted JWTs, called JWE, exist but are rarely needed.)
9. Why is JWT popular? What is its main drawback? Any server with the key can verify a token without a database lookup, which suits APIs, mobile apps and multiple services. The drawback is revocation: a token stays valid until it expires, so access tokens must be short-lived.
10. What is the difference between an access token and a refresh token? The access token is short-lived and sent with every API call. The refresh token is long-lived, sent only to the refresh endpoint, stored server-side so it can be revoked, and rotated on each use.
11. Where should a web app store tokens? There is a trade-off. localStorage is readable by any XSS. An httpOnly, Secure, SameSite cookie cannot be read by scripts but needs CSRF thinking. A common pattern keeps the access token in memory and the refresh token in an httpOnly cookie.
12. What is password hashing, and why hash rather than encrypt? Hashing turns a password into a fixed-length value that cannot be reversed. Encryption can be reversed by anyone with the key, and the server never needs the original password, only a way to check it.
13. What is bcrypt? The original said "a library"; more precisely, bcrypt is a slow, salted password-hashing algorithm with an adjustable cost factor, and bcrypt/bcryptjs are Node.js implementations. Mention the 72-byte input limit, and that OWASP lists Argon2id as the first choice for new systems.
14. What is a salt? A random value generated for each password and stored with the hash. It makes identical passwords produce different hashes and makes precomputed rainbow tables useless. It is not secret.
15. How does bcrypt check a password if the original is not stored? bcrypt.compare reads the salt and cost from the stored hash, hashes the typed password with them, and compares the results. It does not create a fresh random salt.
Common Mistakes (and the Fix)
| Mistake | What happens | Fix |
|---|---|---|
| Storing passwords in plain text "just for now" | Every backup, dump or leak exposes every account, and other sites through password reuse | Hash with bcrypt (cost 10 or more) or Argon2id from the very first commit |
Passing req.headers.authorization straight to jwt.verify | JsonWebTokenError: invalid token because of the "Bearer " prefix, so every request gets 401 | Split the header, check the scheme is Bearer, verify only the token part |
Using jwt.decode() to make access decisions | Forged tokens are accepted; anyone can claim role: "admin" | Always jwt.verify() with the secret and a pinned algorithms list |
Hard-coding a weak secret like "SECRET_KEY" | Anyone who reads the code or guesses the secret can mint admin tokens | A long random value in process.env.JWT_SECRET; refuse to start without it |
| Reading the role from the registration body | Users sign themselves up as admins | Set roles on the server; change them only through an admin-only route |
| Checking the role but not ownership | Any teacher edits any course; any student reads any receipt | Compare the resource's owner with req.user.id, or filter by owner in the query |
My Opinion
Hash passwords from day one, even in a prototype. Adding bcrypt.hash takes two lines. "Just for now" plain-text tables have a way of reaching production, backups and other people's laptops before anyone remembers to fix them.
Do not build your own crypto or token format. Use jsonwebtoken (or jose), bcrypt or argon2, and your framework's session middleware. For anything bigger than a learning project, consider a managed identity provider so MFA, password resets and social login come ready-made and tested.
Choose sessions unless you have a reason for JWT. For one web app on one domain, server-side sessions in Redis are simpler, and logout really logs out. Reach for JWTs when you have mobile clients or several services, and then keep access tokens at 15 minutes or less with rotating refresh tokens.
Write authorization as reusable middleware and test the "no" cases. Most auth bugs are a missing check, not a broken one. For every protected route, write a test that expects 401 without a token and 403 with the wrong user, exactly like the test script above.
Require MFA for admins and staff first. If you can only add MFA for some users, start with the accounts that can see or change everyone else's data. That is where one stolen password does the most damage.
Try It Yourself
Answer these in your own words first, then check. For questions 4 and 5, run the code to confirm.
1. A logged-in student calls DELETE /courses/5. Which status code, and why not 401?
2. Name the three authentication factors. Is "password + date of birth" MFA?
3. A teacher's account is removed at 10:00. Their access token was issued at 09:55 with
expiresIn '15m'. Until when can it still be used, and how would you shorten that window?
4. What does this print?
const p = 'eyJyb2xlIjoic3R1ZGVudCIsInN1YiI6IjcifQ';
console.log(Buffer.from(p, 'base64url').toString());
5. What do these print?
const h = await bcrypt.hash('neha-portal-2026', 10);
console.log(h === await bcrypt.hash('neha-portal-2026', 10));
console.log(await bcrypt.compare('neha-portal-2026', h), bcrypt.getRounds(h));
6. Why does the login route compare against a dummy hash when the email is not found?
7. A product API checks requireRole('vendor') on PUT /products/:id. What is still missing?
8. Rewrite this policy to follow NIST SP 800-63B: "8-16 characters, must include an
uppercase letter, a digit and a symbol, change every 90 days".
Show answers
1. 403 Forbidden. The server knows who the student is (authentication passed); the student
just lacks permission. 401 is for a missing, invalid or expired token.
2. Know (password, PIN), have (phone, security key), are (fingerprint, face).
No: password and date of birth are both "something you know".
3. Until 10:10, when it expires. Shorten access-token lifetime, revoke the refresh token,
and for urgent cases check a deny-list or a per-user "tokens valid after" time.
4. {"role":"student","sub":"7"} (no key needed: base64url is encoding, not encryption)
5. false (a new random salt each time)
true 10
6. So unknown emails take as long to reject as wrong passwords. Otherwise the response
time reveals which emails are registered.
7. An ownership check: load the product and return 403 unless product.vendorId === req.user.id
(or filter the query by vendor), so a vendor cannot edit another vendor's products.
8. At least 15 characters (8 if MFA is required), allow at least 64 characters, all
printable characters and spaces; reject common and breached passwords; no composition
rules; change only when there is evidence of compromise.
Frequently Asked Questions
Is JWT more secure than sessions?
No, they are different, not more or less secure. Both are safe when used correctly over HTTPS. Sessions are easier to revoke; JWTs avoid a lookup per request. Most real-world problems come from implementation mistakes, such as long-lived tokens in localStorage or session cookies without SameSite, rather than from the choice itself.
Should I use bcrypt or bcryptjs?
Use bcrypt if it installs on your machine and servers; it is a native add-on and faster. Use bcryptjs when native modules are a problem (some serverless or Windows setups). Hashes are compatible, so you can switch later without users resetting passwords.
How long should an access token live?
Commonly 5 to 15 minutes for APIs that use refresh tokens, and up to an hour for low-risk apps. The shorter the life, the smaller the damage from a stolen token, but the more refresh calls you make.
Can I log out a user who has a JWT?
You can delete the client's copy and revoke the refresh token, so the session cannot be extended. The current access token keeps working until it expires unless you add a deny-list check. That is the main reason to keep access tokens short.
Where do I put the JWT secret in production?
In an environment variable set by your hosting platform, or in a secrets manager such as AWS Secrets Manager, read once at startup with process.env.JWT_SECRET. Never in code, Git, logs or the front end. If it ever leaks, change it, which logs everyone out.
Key Takeaways
- Authentication proves who you are (
401when it fails); authorization decides what you may do (403when it fails). - MFA combines different factor types, such as a password plus an OTP, and matters most for admin and staff accounts.
- Sessions keep state on the server and are easy to revoke; JWTs carry signed claims and are hard to revoke, so keep them short-lived.
- A JWT is
header.payload.signature; the payload is readable by anyone, and onlyjwt.verify()with a secret fromprocess.envmakes it trustworthy. - Use short access tokens with rotating refresh tokens stored server-side, ideally in an
httpOnly,Secure,SameSitecookie. - Check roles with middleware and ownership in the handler or query, always on the server, and follow least privilege.
- Hash passwords with bcrypt (cost 10 or more; mind the 72-byte limit) or Argon2id; never store, encrypt or log them in plain text.
- Follow NIST: favour length, block breached passwords, and drop composition rules and forced rotation; rate-limit the login route.
Next, read Node.js Error Handling, Logging & File Upload Architecture to see how to log failed logins without ever logging a password, and how to turn the errors from this post into consistent API responses.
References
- NIST SP 800-63B-4: Authentication and Authenticator Management (password rules)
- OWASP Password Storage Cheat Sheet
- RFC 7519: JSON Web Token (JWT)
- MDN: 401 Unauthorized

0 Comments