Authentication — Sessions, JWTs and OAuth
Password hashing, cookie sessions versus JWTs, OAuth sign-in, protecting routes, and the security mistakes to avoid.
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.
| Concept | Question | Planner example |
|---|---|---|
| Authentication | Who is this request from? | Which student session is valid? |
| Authorization | Can they do this? | Does this plan belong to that student? |
| Credential | What proves identity? | Password at sign-in, then a session cookie |
| Session | How is login remembered? | Server-side session record linked to a cookie |
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.
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.
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-off | Server-side session | JWT |
|---|---|---|
| Revocation | Straightforward by invalidating server record | Needs expiry, a denylist, or rotation strategy |
| Server state | Session storage required | Token verification can be local |
| Payload | Opaque ID reveals no claims | Claims are readable unless separately encrypted |
| Good fit | Many browser applications | Defined 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.
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.
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.
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.
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.
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.
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.
- Resolve the session on the server and reject unauthenticated requests.
- Use the trusted identity from the session, not a body field.
- Include ownership or permission conditions in the database query.
- Revoke the server-side session and clear the browser cookie at logout.
- Log security-relevant outcomes without logging passwords, tokens, or cookie values.
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.
Add a Safe Sign-In Boundary
Practice
A session-backed planner account
- Define a password hashing and verification module using bcrypt and configuration for its work factor.
- Sketch sign-up, sign-in, logout, and password reset flows, including rate limits and generic error messages.
- Set and clear an opaque session cookie with HttpOnly, Secure in production, and an intentional SameSite policy.
- Protect a plan API route and scope its Prisma query by the verified session user.
- 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.
Spotted a mistake or something unclear? Suggest a fix on GitHub or email us. Select the text first and it is quoted for you.
Discussion
0Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.
