Authentication — Sessions, JWTs and OAuth

Password hashing, cookie sessions versus JWTs, OAuth sign-in, protecting routes, and the security mistakes to avoid.

Est. 40 min Updated Suggest a fix
// Part 01 — Identity

Authentication Is Not the Same as Authorization

Authentication answers who is making a request. Authorization answers whether that person may perform a particular action on a particular resource. A student can be signed in and still have no permission to read another student's study plan. Every server-side read and write needs an ownership or role check appropriate to the action.

For this planner, an authenticated identity should come from a verified session or token. It must not come from a user ID, email, or role in the request body. The browser is controlled by the user; the server decides which identity and permissions to trust.

ConceptQuestionPlanner example
AuthenticationWho is this request from?Which student session is valid?
AuthorizationCan they do this?Does this plan belong to that student?
CredentialWhat proves identity?Password at sign-in, then a session cookie
SessionHow is login remembered?Server-side session record linked to a cookie
⚠️ Important
A hidden button or unguessable URL is not access control. Check authorization at the server boundary on every sensitive operation.
// Part 02 — Passwords

Hash Passwords with a Purpose-Built Algorithm

Never store a plaintext password or a reversible encrypted password. Password hashing algorithms are deliberately expensive and use a salt so identical passwords do not produce the same stored hash. Use a maintained library such as bcrypt, choose its work factor using current guidance and your performance budget, and never write your own password-hashing scheme.

src/auth/passwords.ts
typescript
import bcrypt from "bcrypt"

const workFactor = Number(process.env.BCRYPT_WORK_FACTOR)
if (!Number.isInteger(workFactor) || workFactor < 10) {
  throw new Error("Configure a valid bcrypt work factor")
}

export async function hashPassword(password: string): Promise<string> {
  if (password.length < 12 || password.length > 200) {
    throw new Error("Password does not meet the length policy")
  }
  return bcrypt.hash(password, workFactor)
}

export async function verifyPassword(password: string, hash: string): Promise<boolean> {
  return bcrypt.compare(password, hash)
}

The numeric threshold shown in the example is an application policy illustration, not a universal password rule. Select a work factor based on current bcrypt guidance and benchmark it on the production class of machine. Rate-limit sign-in attempts, use generic failure messages so account existence is not revealed, and consider a password reset flow that invalidates existing sessions when appropriate.

🎯 Pro Tip
Use an established authentication library when possible. A few lines of hashing code do not make a complete account system; reset flows, session expiry, brute-force controls, and secure recovery also matter.
// Part 03 — Sessions and JWTs

Choose a Credential Model for the Application

With a traditional session, the server stores session state and the browser holds a random opaque identifier in a cookie. The server can revoke that identifier by deleting or expiring the record. A JSON Web Token (JWT) is a signed token that carries claims; it can be verified without a database lookup, but revocation and key rotation require additional design. Neither approach is automatically secure or automatically stateless at the application level.

Trade-offServer-side sessionJWT
RevocationStraightforward by invalidating server recordNeeds expiry, a denylist, or rotation strategy
Server stateSession storage requiredToken verification can be local
PayloadOpaque ID reveals no claimsClaims are readable unless separately encrypted
Good fitMany browser applicationsDefined service-to-service or distributed use cases

For a browser-first study planner, an opaque server-side session is often easier to revoke and reason about. A JWT is a signed format, not a place to store a password or secret, and signing does not encrypt its contents.

// Part 04 — Cookies

Protect Browser Sessions with Cookie Attributes

Set session cookies from the server with HttpOnly so JavaScript cannot read them, Secure so they travel only over HTTPS, and an intentional SameSite policy. Scope the cookie narrowly and expire it appropriately. An HttpOnly cookie reduces one way to steal a credential, but it does not prevent cross-site request forgery by itself.

src/auth/session-cookie.ts
typescript
import type { Response } from "express"

export function setSessionCookie(response: Response, sessionId: string) {
  response.cookie("study_session", sessionId, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "lax",
    path: "/",
    maxAge: 1000 * 60 * 60 * 24 * 7,
  })
}

export function clearSessionCookie(response: Response) {
  response.clearCookie("study_session", {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "lax",
    path: "/",
  })
}

Cookie options must match the browser and deployment topology. HTTPS is required in production. Keep the cookie value random and meaningless, store only a hash of the session identifier if the session store supports it, rotate identifiers after sign-in or privilege changes, and invalidate them on logout.

💡 Note
Cookie expiry is not a substitute for server-side expiry. Validate that the session is active, not expired, and not revoked each time it is used.
// Part 05 — CSRF

Understand Cross-Site Request Forgery

Browsers automatically attach matching cookies to requests, including some requests initiated by another site. An attacker may try to trick a signed-in browser into submitting an unwanted action. SameSite cookies help, but design still needs defense in depth: avoid state changes on GET, verify origin where appropriate, use a CSRF token for relevant cross-site form flows, and require appropriate content types.

src/middleware/require-origin.ts
typescript
import type { Request, Response, NextFunction } from "express"

const trustedOrigin = process.env.APP_ORIGIN

export function requireTrustedOrigin(
  request: Request, response: Response, next: NextFunction,
) {
  if (["GET", "HEAD", "OPTIONS"].includes(request.method)) {
    next()
    return
  }

  const origin = request.get("origin")
  if (!trustedOrigin || origin !== trustedOrigin) {
    response.status(403).json({ error: "Request origin is not allowed" })
    return
  }
  next()
}

This origin check is an illustrative layer and does not replace a carefully implemented CSRF strategy for every app architecture. OAuth callbacks, native clients, same-origin deployments, and cross-origin APIs can have different requirements. Define the allowed origins explicitly; do not reflect arbitrary Origin values into an allowlist.

// Part 06 — Protect data

Authenticate and Authorize Every Data Access

A middleware can resolve a session and attach a trusted user to the request. The service must still scope database queries by that user. Checking ownership in one route but not another creates an insecure direct object reference. Use the same authorization-aware data access pattern for page rendering, APIs, exports, and background operations.

src/routes/owned-plans.ts
typescript
router.get("/:planId", requireSession, asyncHandler(async (request, response) => {
  const plan = await prisma.studyPlan.findFirst({
    where: {
      id: request.params.planId,
      ownerId: request.user.id,
    },
    select: { id: true, title: true, examDate: true },
  })

  if (!plan) {
    response.status(404).json({ error: "Study plan not found" })
    return
  }
  response.json({ plan })
}))

Returning not found for both a missing plan and a plan owned by someone else can reduce resource enumeration. Whether to distinguish them is a product and threat-model decision. In either case, never return the record before the ownership filter has been applied.

  1. Resolve the session on the server and reject unauthenticated requests.
  2. Use the trusted identity from the session, not a body field.
  3. Include ownership or permission conditions in the database query.
  4. Revoke the server-side session and clear the browser cookie at logout.
  5. Log security-relevant outcomes without logging passwords, tokens, or cookie values.
// Part 07 — Pitfalls

Common Mistakes

Storing a plaintext password or reversible password encryption

Why: A database leak exposes credentials that can be reused elsewhere.

Fix: Use a maintained password-hashing library with a calibrated cost.

Putting a JWT in localStorage by default

Why: Any script running in the origin can read it after an XSS flaw.

Fix: Choose a credential design deliberately; browser sessions often fit HttpOnly cookies.

Treating authentication as authorization

Why: Any signed-in student might then access another student’s records.

Fix: Check ownership or permissions for every operation.

Assuming SameSite or HttpOnly solves every browser threat

Why: CSRF and script injection are different threat classes.

Fix: Use layered CSRF defenses, output safety, HTTPS, and restrictive cookie settings.

// Part 08 — Practice

Add a Safe Sign-In Boundary

Practice

A session-backed planner account

  1. Define a password hashing and verification module using bcrypt and configuration for its work factor.
  2. Sketch sign-up, sign-in, logout, and password reset flows, including rate limits and generic error messages.
  3. Set and clear an opaque session cookie with HttpOnly, Secure in production, and an intentional SameSite policy.
  4. Protect a plan API route and scope its Prisma query by the verified session user.
  5. Write a short CSRF threat model for the app and identify where origin checks or CSRF tokens are needed.

Hint: Do not implement production authentication from this lesson alone. Prefer a maintained auth framework and test cookie behavior over HTTPS.

🎯 Key Takeaways

  • ✓Authentication identifies the caller; authorization decides what that caller may do.
  • ✓Hash passwords with a purpose-built, maintained algorithm and calibrate its cost.
  • ✓Sessions are revocable server-side records; JWTs are signed claims with different trade-offs.
  • ✓Secure cookies use deliberate HttpOnly, Secure, SameSite, path, and expiry settings.
  • ✓Cookie-based applications need a CSRF strategy; HttpOnly does not stop CSRF.
  • ✓Scope every sensitive query and mutation to the authenticated user or an explicit permission.
  • For production, use a maintained authentication library and consult its current security guidance. Do not log passwords, authorization headers, session IDs, or tokens.

Next

What comes next

Prevent cross-site scripting, cross-site request forgery and injection, configure CORS and security headers, and handle secrets safely.

Lesson 09 · Web Security for Full-Stack Developers — XSS, CSRF and CORS →

HELP US IMPROVE

How was this lesson?

Your note is shared with the Chaduvuko team for review. Please don’t include personal or sensitive information.

Choose your feedback

Spotted a mistake or something unclear? Suggest a fix on GitHub or email us. Select the text first and it is quoted for you.

Share

Discussion

0

Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.

Continue with GitHub
Loading...