Authentication answers "who is this?" Authorization answers "may they do this?" Session management connects the two across many requests. Bugs in any of the three hand an attacker someone else's account or data, and broken access control has been the top category of the OWASP Top 10 since 2021. This lesson builds each piece on the server: a sign-in flow that resists guessing and doesn't reveal which accounts exist, a password reset that can't be abused, sessions that rotate and expire, and authorization checks on every object.
Before you start
Read Passwords, Passkeys, and Multi-Factor Authentication Explained for password storage and MFA, and OWASP Top 10 Explained for the risk categories. Examples use TypeScript with Express-style handlers and a PostgreSQL database through Prisma.
Sign-in that resists guessing
A sign-in endpoint faces two automated attacks: brute force (many passwords against one account) and credential stuffing (leaked email and password pairs from other sites, tried across many accounts). Defend against both:
- Rate limit by account and by source. For example, slow down after five failures for one account within 15 minutes, and limit total attempts per IP address. Store counters in the database or a shared store, not in one server's memory, so limits survive restarts and apply across instances.
- Use uniform responses. "Invalid email or password" for every failure, with similar timing, so attackers can't confirm which emails are registered.
- Offer MFA and passkeys, and require phishing-resistant MFA for administrators.
- Notify users of sign-ins from new devices and of security changes.
export async function signIn(email: string, password: string, ip: string) {
if (await tooManyAttempts({ email, ip })) return { ok: false, error: "Too many attempts. Try again later." } as const;
const user = await db.user.findUnique({ where: { email: email.trim().toLowerCase() } });
// Verify against a dummy hash when the user doesn't exist, so timing doesn't reveal it.
const valid = await verifyPassword(user?.passwordHash ?? DUMMY_ARGON2ID_HASH, password);
if (!user || !valid || user.disabledAt) {
await recordFailedAttempt({ email, ip });
return { ok: false, error: "Invalid email or password." } as const;
}
await clearFailedAttempts({ email });
return { ok: true, user } as const;
}Avoid locking accounts permanently after a few failures; that lets anyone lock out any user. Temporary, increasing delays are safer.
Password reset without leaks
A reset flow is an alternative way to sign in, so it needs the same care:
- The user enters an email. Always reply "If an account exists, we've sent a link," whether or not it does.
- Generate a random token of at least 128 bits, store only its hash with the user ID and an expiry (for example, 30 to 60 minutes), and email a link containing the token.
- When the link is used, hash the token, look it up, check expiry, let the user set a new password, then delete the token and every other outstanding reset token for that user.
- End all existing sessions for the account, and email a notification that the password changed.
import { createHash, randomBytes } from "node:crypto";
const sha256 = (value: string) => createHash("sha256").update(value).digest("hex");
export async function createResetToken(userId: string) {
const token = randomBytes(32).toString("base64url");
await db.passwordReset.create({
data: { userId, tokenHash: sha256(token), expiresAt: new Date(Date.now() + 30 * 60_000) },
});
return token; // goes only into the emailed link, never into logs
}
export async function consumeResetToken(token: string) {
const record = await db.passwordReset.findUnique({ where: { tokenHash: sha256(token) } });
if (!record || record.expiresAt < new Date()) return null;
await db.passwordReset.deleteMany({ where: { userId: record.userId } });
return record.userId;
}Storing a hash means a database leak doesn't hand out working reset links. Build the link from a configured base URL, never from the request's Host header, which an attacker can change to send users a link to their own server. Keep the token out of analytics and referrer headers by not loading third-party scripts on the reset page and sending Referrer-Policy: no-referrer.
Session management
After sign-in, the server needs to recognize the user on each request. The robust default for web applications is a server-side session: a random session ID in a cookie, and a row in a session store that holds the user ID, creation time, last activity, and any security context.
Create and rotate
- Generate the session ID from a cryptographically secure random generator with at least 128 bits of entropy.
- Issue a new session ID at sign-in and whenever privileges change (for example, after MFA or when switching to an admin role). Reusing a pre-login ID enables session fixation, where an attacker plants a known ID in the victim's browser before they sign in.
- Set the cookie with
Secure,HttpOnly,SameSite=LaxorStrict, and the__Host-prefix.
import { createHash, randomBytes } from "node:crypto";
const hash = (id: string) => createHash("sha256").update(id).digest("hex");
export async function startSession(res: Response, userId: string) {
const id = randomBytes(32).toString("base64url");
await db.session.create({
data: { idHash: hash(id), userId, expiresAt: new Date(Date.now() + 12 * 3600_000), lastSeenAt: new Date() },
});
res.cookie("__Host-session", id, { httpOnly: true, secure: true, sameSite: "lax", path: "/" });
}
export async function currentSession(id: string | undefined) {
if (!id) return null;
const session = await db.session.findUnique({ where: { idHash: hash(id) }, include: { user: true } });
const idleLimit = 60 * 60_000; // 1 hour without activity
if (!session || session.expiresAt < new Date() || Date.now() - session.lastSeenAt.getTime() > idleLimit) return null;
return session;
}Storing a hash of the session ID, like the reset token, means a leaked session table can't be used to hijack sessions.
Expire and revoke
Sessions need two timeouts: an idle timeout (for example, one hour without activity for sensitive applications) and an absolute timeout (for example, 12 hours or a few days) after which the user must sign in again. Pick values that fit the risk; a banking app and a recipe site differ. Sign-out must delete the session on the server, not only the cookie in the browser. Offer users a list of active sessions with a "sign out everywhere" button, and revoke all sessions on password change, MFA reset, or account disablement.
What about JWTs?
JSON Web Tokens are often used as session tokens because they're self-contained. The trade-off is revocation: a signed token stays valid until it expires, even after sign-out, unless you add a server-side check, which removes the main advantage. For browser sessions in a single application, a server-side session in an HttpOnly cookie is simpler and easier to revoke. Lesson 10 covers when tokens fit and how to validate them.
Authorization: checking every request
Authorization must happen on the server, for every request, close to the data. A useful mental model is three questions, in order:
- Who is this? A valid session or token, or the request is unauthenticated.
- May this kind of user perform this action? Function-level authorization: only admins may delete users; only editors may publish.
- May this user act on this specific object? Object-level authorization: this invoice, document, or order belongs to them or their organization.
The third check is where most real bugs are. Changing /api/invoices/1043 to /api/invoices/1044 is called an insecure direct object reference (IDOR), and it works whenever the server checks the first two questions but not the third.
Scope queries to the user
The most reliable pattern is to put the ownership condition into the query itself, so a missing check returns nothing rather than someone else's data:
export async function getInvoice(session: Session, invoiceId: string) {
return db.invoice.findFirst({
where: { id: invoiceId, organizationId: session.organizationId },
});
}
app.get("/api/invoices/:id", requireSession, async (req, res) => {
const invoice = await getInvoice(req.session, req.params.id);
if (!invoice) return res.sendStatus(404); // same answer for "missing" and "not yours"
res.json(toInvoiceResponse(invoice));
});Returning 404 for objects the user can't see avoids confirming that they exist. Random, unguessable IDs (such as UUIDs) make enumeration harder, but they're not a substitute for the check: IDs leak through URLs, logs, and shared links.
Centralize the rules
Scattered if (user.role === "admin") checks are easy to forget in a new route. Put permissions in one place and deny by default:
type Action = "invoice.read" | "invoice.update" | "user.delete";
const ROLE_PERMISSIONS: Record<string, readonly Action[]> = {
member: ["invoice.read"],
billing: ["invoice.read", "invoice.update"],
admin: ["invoice.read", "invoice.update", "user.delete"],
};
export function can(role: string, action: Action): boolean {
// Object.hasOwn: unknown roles, and inherited keys such as "constructor", get nothing.
return Object.hasOwn(ROLE_PERMISSIONS, role) && ROLE_PERMISSIONS[role]!.includes(action);
}
export const requirePermission = (action: Action) => (req: Request, res: Response, next: NextFunction) =>
can(req.session.user.role, action) ? next() : res.sendStatus(403);Roles answer question 2; query scoping answers question 3. You need both. Also guard mass assignment: never pass a request body straight into an update, or a user can set role: "admin" on themselves. Pick the allowed fields explicitly.
Testing authorization
Automated scanners rarely find authorization bugs because they don't know who should see what. Write tests with two users in two organizations:
it("doesn't let one organization read another's invoice", async () => {
const alice = await signInAs("alice@org-a.test");
const bobInvoice = await createInvoiceFor("bob@org-b.test");
const res = await alice.get(`/api/invoices/${bobInvoice.id}`);
expect(res.status).toBe(404);
});
it("refuses user deletion to non-admins", async () => {
const member = await signInAs("member@org-a.test");
const res = await member.post("/api/admin/users/someone/delete");
expect(res.status).toBe(403);
});Add one such test for every endpoint that reads or changes an object, and run them in CI.
Common mistakes and troubleshooting
- Checking roles but not ownership. Every object lookup needs the user or organization in the query.
- Hiding admin links instead of protecting routes. Anyone can send the request directly.
- Different errors for "wrong password" and "no such user". Unify messages and timing.
- Keeping the pre-login session ID. Rotate at sign-in and on privilege changes.
- Sign-out that only deletes the cookie. Delete the server-side session.
- Reset tokens in plain text or without expiry. Hash them, expire them, use them once.
- Updating with the whole request body. Allowlist the fields a user may change.
If users complain of being signed out too often, check that the idle timeout updates lastSeenAt on activity, and that multiple servers share the same session store.
Practical exercise: secure a small app
In a local practice project with users, organizations, and a resource such as notes:
- Implement sign-in with uniform errors and a database-backed attempt counter.
- Implement password reset with hashed, expiring, single-use tokens that revoke sessions.
- Store sessions server-side with idle and absolute timeouts, and rotate the ID at sign-in.
- Scope every note query to the user's organization, and add a
can()permission check for deleting notes. - Write the two-user tests and confirm they fail if you remove the scoping.
Key takeaways
- Rate limit sign-in by account and source, and give uniform errors.
- Password reset tokens should be random, hashed, short-lived, single-use, and revoke existing sessions.
- Server-side sessions with rotation, idle and absolute timeouts, and real sign-out are the simplest robust choice for web apps.
- Check authorization on every request: who, what action, and which object; scope queries to the user.
- Test authorization with two users in two organizations.
References
- OWASP Authentication Cheat Sheet (opens in a new tab)
- OWASP Session Management Cheat Sheet (opens in a new tab)
- OWASP Forgot Password Cheat Sheet (opens in a new tab)
- OWASP Authorization Cheat Sheet (opens in a new tab)
- OWASP ASVS 5.0: V6 Authentication, V7 Session Management, V8 Authorization (opens in a new tab)
- NIST SP 800-63B-4: Authentication and Authenticator Management (opens in a new tab)
What's next
The same principles apply when your clients are mobile apps, partner systems, and scripts instead of browsers. API Security: Protecting Tokens, Secrets, and Sensitive Data applies them to APIs, using the OWASP API Security Top 10.

