What it is
An authentication handler coordinates credential verification, session creation, and a response. Middleware or a shared request helper then authenticates each protected request. Reusing this work reduces inconsistent checks, but resource authorization still belongs in the request’s policy context.
Why you need it
Writing a different login check for every endpoint makes omissions likely. A central identity check plus explicit resource policy gives you a repeatable structure to test.
How it works
- Apply request size limits, input validation, and login abuse controls.
- Verify the submitted credential through the authentication service.
- Rotate the session identifier when establishing authenticated state.
- Set the cookie; protected requests resolve the session and then authorize the resource.
The boundary between identity and business logic
POST /login:
validateInput(request.body)
enforceLoginLimits(request)
user = verifyCredentials(request.body)
session = createFreshSession(user.id)
setProtectedCookie(session.token)
GET /invoices/:id:
user = requireActiveSession(request)
invoice = loadInvoice(request.params.id)
requirePermission(user, "read", invoice)
return allowedInvoiceFields(invoice)The downloadable lab implements the underlying model as executable Node.js functions. A deployed service also needs an HTTP framework, durable shared storage, cookie/CSRF handling, secret management, and operational abuse controls.
Download the file and run node backend-auth.mjs with Node.js 22 or newer. It tests an in-memory auth model; it is not a production login server.
Good practices and why
- Use an established auth library or identity provider where it fits; keep authentication policy separate from presentation.
- Reject unknown, expired, or revoked sessions before executing protected work; define behavior when the session store is unavailable.
Common mistakes
- Accepting a session identifier chosen by the client when logging in.
- Adding middleware to read routes but forgetting exports, updates, or nested routes.
Try it yourself
Run backend-auth.mjs with Node. Follow login → authenticate → readInvoice, then add a second protected function using the same authentication check.
What a successful result looks like
Your function works for an active session and fails for an unknown, expired, or revoked token without exposing protected data.
0 / 6000 characters · Saved on this device. Do not include passwords or private data.
Check your understanding
Answer the understanding check correctly to record exercise completion.
Related interview practice
These scenarios add constraints and follow-up questions to the concepts you just learned.
Further reading
- OWASP: authentication ↗
- OWASP: password storage ↗
- OWASP: session management ↗
- MDN: Set-Cookie ↗
- IETF: JWT best current practices ↗
Selected primary references · reviewed 2026-10-09. Examples are educational; use your framework’s documented integration guidance when building a deployed system.