Chapter 09 / 15 · Webster International
Authentication, Sessions & Security
Identity, permissions, cookies, session tokens, OAuth, JWTs, CSRF/XSS, secret handling, privacy, threat modelling and secure design.
Authentication proves who is calling. Authorisation decides what that identity may do. Encryption protects information in transit or at rest. They are separate concerns.
01 / FIELD NOTE
Identity versus authorisation
Mental model: authentication establishes a principal; authorisation evaluates a predicate over that principal, action, tenant, resource and current policy. A successful login is never a blanket capability. Deny by default, and constrain the resource lookup by authorised tenant ID. Check every API route, worker and export—not merely visible buttons.
A valid login must not allow a user to guess another client's invoice ID. Tenant isolation protects confidentiality and integrity even when object identifiers are sequential. Negative cross-tenant tests are a release requirement.
Example A: GET /projects/42/invoices/13 checks the user's project 42 membership and invoice 13's project ownership. Example B: POST /projects/8/bookings/91/cancel must reject a manager who belongs only to project 7, even if booking 91 exists.
// ILLUSTRATIVE: db and actor permissions are application-specific.
async function readInvoice(db, actor, projectId, invoiceId) {
if (!actor?.permissions?.includes('invoice:read')) throw Error('Forbidden');
if (!actor.projectIds.includes(projectId)) throw Error('Forbidden');
return db.get('SELECT id, total FROM invoices WHERE id=? AND project_id=?', [invoiceId, projectId]);
}Hands-on exercise · reveal the verification check
Build four negative/positive cases: authorised invoice, same invoice from another tenant, missing invoice, and anonymous request. Repeat against a CSV export.
Only the authorised request returns data; cross-tenant and anonymous requests are rejected, missing IDs yield no record, and export obeys the same policy.
02 / FIELD NOTE
Session cookies and random tokens
Mental model: a cookie session is a bearer reference to server-controlled identity, not the user record itself. Generate an opaque random ID with a CSPRNG, store a protected verifier server-side, rotate after login or privilege changes, and revoke on logout. Apply idle and absolute server-side deadlines. A __Host- cookie requires Secure, Path=/ and no Domain; HttpOnly blocks ordinary JavaScript reads, while SameSite limits some cross-site sends.
A stolen session ID impersonates the user until revoked or expired. Server-side invalidation limits replay; cookie attributes reduce exposure but cannot prevent all XSS or CSRF. Warn accessibly before expiry and avoid silently discarding unsent forms.
Example A: an HTTPS admin portal sends Set-Cookie: __Host-session=<opaque>; Secure; HttpOnly; SameSite=Lax; Path=/. Example B: a staff member promoted to billing administrator receives a new session ID and the old ID stops working.
// RUNNABLE: save as session-demo.cjs; node session-demo.cjs
const {randomBytes}=require('node:crypto');
const id=randomBytes(32).toString('base64url');
console.log('Decoded token bytes:',Buffer.from(id,'base64url').length);
// Never print real production session IDs in logs.Hands-on exercise · reveal the verification check
Test login, permission elevation, logout, idle timeout and absolute timeout. Attempt to reuse each old test token.
The demo prints 32. Every old or expired test token is rejected; a new token appears after privilege change; cookie flags match the intended host-only policy.
03 / FIELD NOTE
JWTs, OAuth 2.0 and OpenID Connect
Mental model: OAuth 2.0 grants delegated resource access; OpenID Connect adds an identity layer; JWT is only a token format. Decoding a JWT is not cryptographic verification. An API must validate trusted signature/key, issuer, audience, expiry, permitted algorithm and required scopes. Public clients use authorisation code plus PKCE and registered exact redirect URIs; state guards the login transaction.
A calendar integration should read only granted events without receiving account passwords. Valid tokens from the wrong provider, for another API, or with insufficient scopes must not become universal credentials.
Example A: a mobile booking app uses authorisation code plus PKCE, then presents a scoped access token to the bookings API. Example B: a reporting service gets read:events but cannot use an ID token as an API access token or call write:events.
// ILLUSTRATIVE only: trustedVerifier must perform real JOSE verification.
async function authorize(raw, trustedVerifier) {
const c=await trustedVerifier.verify(raw,{issuer:'https://id.example.test/',audience:'bookings-api',algorithms:['RS256']});
if(!c.scope?.split(' ').includes('bookings:read')) throw Error('Forbidden');
return c.sub;
}Hands-on exercise · reveal the verification check
Diagram browser → identity provider → callback → API with state, PKCE and code exchange. Test wrong issuer, wrong audience, expired token and missing scope.
Only a cryptographically verified token from the expected issuer for bookings-api with bookings:read passes; every negative case fails.
04 / FIELD NOTE
Password hashing and multifactor authentication
Mental model: a password verifier is an intentionally costly salted one-way function, not reversible encryption or fast SHA-256. Use a maintained Argon2id library with unique salts and benchmarked parameters; OWASP lists 19 MiB, t=2, p=1 among minimum configurations, not an optimum for every host. Pair it with breached-password checks, throttling and phishing-resistant MFA where feasible. Reset tokens are one-time, short-lived random capabilities.
A database leak should not instantly expose reusable passwords. Stronger MFA reduces phishing risk, while accessible sign-in must support password managers and paste rather than memory puzzles.
Example A: a CRM verifies an Argon2id password, throttles failed attempts and rotates the session on login. Example B: a reset link is redeemed once, expires quickly, and returns the same public response whether the email is registered or not.
// ILLUSTRATIVE: use a maintained Argon2id library, not a hand-rolled hash.
// const argon2=require('argon2');
// const stored=await argon2.hash(password,{type:argon2.argon2id});
// const valid=await argon2.verify(stored,candidate);
// Never log password, candidate or stored verifier.Hands-on exercise · reveal the verification check
Test reset requests for unknown/known email, expired token, reused token and two simultaneous redemptions; measure verifier latency under concurrency.
Public responses do not enumerate accounts; only one valid redemption succeeds; paste/autofill works; measured latency stays within an agreed capacity budget.
05 / FIELD NOTE
XSS, CSRF and input boundaries
Mental model: XSS crosses the untrusted-data-to-executable-code boundary; CSRF exploits ambient browser cookies to submit an unintended authenticated request. Use textContent or context-appropriate output encoding for untrusted text; sanitise only intentionally supported rich HTML. Protect cookie-authenticated mutations with CSRF tokens or robust Origin/Fetch Metadata validation with legacy fallback. Input validation alone is not output encoding.
One hostile client note can execute in the trusted origin; a forged payment request can mutate data while the victim is logged in. Both bypass assumptions that a correct password or role check is enough.
Example A: a client note containing <img onerror=...> must render as literal text, not markup. Example B: a cross-site POST /invoices/13/pay with a valid ambient session cookie but missing CSRF token must be rejected.
// RUNNABLE in browser console on a page with #client-note.
const el=document.querySelector('#client-note');
if(el) el.textContent='<img src=x onerror=alert(1)>';
// The characters appear literally; no image or handler executes.
// Server must independently validate CSRF on cookie-authenticated writes.Hands-on exercise · reveal the verification check
Render a hostile note and submit a mutation with missing, invalid and valid CSRF tokens; inspect DOM, server state and accessible errors.
No script runs; missing/invalid CSRF requests leave state unchanged; the valid authorised request succeeds and feedback is perceivable.
06 / FIELD NOTE
Secrets, encryption and least privilege
Mental model: each secret is a scoped, revocable capability with an owner, lifetime, rotation plan and audit trail. Keys, access tokens and passwords are different objects. Store them in managed server-side storage, never frontend bundles, git history, container layers or logs. Use TLS in transit, authenticated encryption for selected sensitive fields and separate workload identities with least privilege.
Minification cannot hide a browser API key. Per-service permissions contain compromises, while planned rotation and revocation enable recovery without taking the entire system offline.
Example A: a nightly reporting job gets SELECT access to approved views, never schema-migration privileges. Example B: a webhook verification secret lives in server storage, rotates with a tested overlap window and is never delivered to the browser.
// ILLUSTRATIVE Node server configuration, never browser code.
function requireWebhookSecret(){
const value=process.env.WEBHOOK_VERIFY_SECRET;
if(!value) throw Error('Webhook secret missing');
return value; // use in vetted verifier, never log
}Hands-on exercise · reveal the verification check
Inventory five credentials with owner, scope, storage, rotation, revocation and detection. Revoke one staging-only credential and restore via replacement.
No secret appears in browser assets or logs; revoked access fails, replacement restores only the intended service, and audit events contain no secret value.
07 / FIELD NOTE
Threat modelling and dependency hygiene
Mental model: threat modelling traces assets and data flows across trust boundaries, then asks how an adversary could spoof, tamper, repudiate, disclose, deny service or elevate privilege (STRIDE). It is a design activity, not a green dependency-scan badge. Prioritise risks by likelihood and impact, attach controls and negative tests, and revisit after data-flow or dependency changes.
Scanners rarely detect business-logic abuse, unsafe uploads or confused-deputy integrations. Finding those threats before deployment is cheaper than responding after client data is exposed.
Example A: an image uploader enforces authentication, size/type limits, isolated decoding, quota and private object ACL. Example B: an event importer treats third-party URLs as hostile and blocks internal-network fetches and unverified outbound links.
// ILLUSTRATIVE threat-model inventory, not an upload implementation.
const boundary={asset:'private photo',entry:'POST /uploads',
trust:'browser -> API -> isolated decoder -> object store',
threats:['oversized input','malformed media','cross-tenant read'],
controls:['authz','quota','sandbox','private ACL'],
evidence:['negative upload tests','tenant isolation test']};Hands-on exercise · reveal the verification check
Draw upload and public-importer flows. Identify three STRIDE/abuse cases at each trust boundary, with owner, mitigation and negative test.
Every high-impact risk has a specific control and a failing-before/fixed-after test; no scanner status is treated as proof of business-logic safety.
08 / FIELD NOTE
Privacy, audit trails and retention
Mental model: debug logs answer what failed; audit records answer who changed which protected object, when and under what authority. Both need purpose, schemas, access control and retention, but audits need integrity protections beyond ordinary debug rotation. Minimise personal data: record actor ID, resource ID, action, time, outcome and correlation ID—not cookies, passwords or full request bodies.
Financial and booking changes need accountability without turning observability into another private-data leak. Retention, deletion and restricted access affect legal exposure, storage cost and incident response.
Example A: invoice audit stores actor_id, invoice_id, status change, timestamp and request_id without card numbers. Example B: dog-booking cancellation records who cancelled and when, while verbose debug traces expire on a shorter schedule.
// RUNNABLE in Node: allowlist the event fields.
const audit=({actorId,invoiceId,action,requestId})=>({
actor_id:String(actorId),resource_id:String(invoiceId),
action:String(action),request_id:String(requestId),
at:new Date().toISOString()});
console.log(audit({actorId:7,invoiceId:13,action:'paid',requestId:'req-42',password:'discard-me'}));
// Production: validate values, encode output and protect storage.Hands-on exercise · reveal the verification check
Design separate audit/debug schemas and retention policies; feed an event containing a password, session token and newline to the pipeline.
Password and session token are excluded; control characters cannot corrupt downstream display; authorised reviewers can trace the change; both datasets have access and retention rules.
RESEARCH EXPANSION · APPLIED ENGINEERING
OWASP ASVS 5.0 as a real test checklist
The Application Security Verification Standard provides testable requirements for architecture, authentication, sessions, access control, input safety and more. Its stable 5.0.0 release was published May 2025.
Specific checks are stronger than generic 'secure the app' aspirations.
Map login, password reset, role checks and audit logging to selected ASVS requirements, noting what was tested.
Hands-on exercise · reveal the verification check
Pick 10 applicable controls and assign test cases and owners.
Evidence references actual test outcomes, not a badge.
Session lifecycle, idle and absolute expiry
Set server-enforced inactivity expiry, absolute lifetime, secure random opaque tokens and session rotation after authentication or privilege change. Logout must revoke the session, not only clear browser display.
Stolen or forgotten sessions can remain useful long after the intended sign-in.
Force re-authentication for account settings after an appropriate idle period; verify the old session cookie no longer works.
Hands-on exercise · reveal the verification check
Test idle expiry, logout, parallel sessions and privilege escalation.
A revoked cookie cannot access protected APIs.
CSRF, XSS and safe template rendering
Cookie-based authentication needs CSRF protections for state-changing requests; template output must be encoded for its context. Use textContent for untrusted user data and sanitise rich HTML with a well-maintained policy.
One injected script can act as the victim or steal sensitive page data despite otherwise valid access controls.
Escape event descriptions and validate state-changing request origin/token; test a malicious `<img onerror>` string as plain text.
Hands-on exercise · reveal the verification check
Submit a markup injection fixture to an event comment field.
The browser displays it as text with no script execution.
Least privilege and service-to-service credentials
Give import jobs, background workers, browser clients and admins different credentials and narrowly scoped roles. Rotate and audit secrets, never expose them in bundles or AI transcripts, and validate access at each boundary.
A breached research scraper should not gain invoice-write permission.
The town-news crawler receives read-only source access and an import-specific write token with no CRM role.
Hands-on exercise · reveal the verification check
Document the minimal permissions for four app components.
A compromised least-privileged component cannot modify unrelated data.
Password reset and anti-enumeration behaviour
Use short-lived single-use reset tokens, generic public responses, throttling, session revocation decisions and a secure delivery channel. Never email plaintext passwords or set permanent predictable temporary credentials.
Password-reset endpoints can be abused to discover users or take over accounts.
Always return a neutral confirmation for known/unknown addresses, while sending only to existing verified accounts.
Hands-on exercise · reveal the verification check
Test expired, reused and guessed tokens.
Each token authorises at most one valid reset within its window.
Security tests at the object boundary
Test roles, tenants and individual record ownership—not only whether routes require login. Include mass-assignment checks so clients cannot set privileged fields by adding them to JSON.
A valid authenticated request may still be a forbidden business action.
Attempt to POST an event with an arbitrary approved=true field; server ignores/rejects rather than silently elevating trust.
Hands-on exercise · reveal the verification check
Build a matrix of 3 roles × 5 API actions.
Every disallowed combination returns the expected denial.
15 / FIELD NOTE
Authentication, resource authorization and tenant isolation
Authentication proves identity; authorization checks each requested resource and action. A user can be validly logged in yet forbidden from accessing another customer's records. Test isolation in workers, APIs and caches, not merely UI routing.
Object-level authorization is a core defense for a shared service-business CRM.
Use two tenant accounts and verify neither can read or edit the other's appointments by changing URL IDs.
-- Every scoped read must enforce tenant identity.
SELECT * FROM bookings WHERE tenant_id = $1 AND id = $2;Hands-on exercise · reveal the verification check
Write negative tests for cross-tenant GET, PATCH and list endpoints.
All unauthorized operations fail at the server.
16 / FIELD NOTE
Secure cookies, session rotation, logout and CSRF
Use Secure and HttpOnly cookie attributes appropriately, select SameSite behavior based on the application's cross-site interactions and use CSRF protection for vulnerable cookie-authenticated state changes. Rotate sessions after important auth transitions and revoke server records on logout.
Security depends on the whole session lifecycle rather than one token format.
Create a login flow that rotates the session, rejects expired sessions and makes logout effective server-side.
Set-Cookie: sid=opaque; Secure; HttpOnly; SameSite=Lax; Path=/Hands-on exercise · reveal the verification check
Inspect browser cookie flags and test invalidated sessions.
A logged-out session cannot still modify a booking.
17 / FIELD NOTE
OAuth 2.0, OIDC, PKCE, issuer and audience validation
OAuth delegates resource access while OpenID Connect adds identity claims. Authorization Code with PKCE protects public clients; servers must validate relevant signatures, issuer, audience and expiry and keep scopes narrow.
Confusing access tokens with identity tokens leads to insecure trust decisions.
Integrate one OIDC provider and validate its ID token separately from an API-scoped access token.
// Validate token issuer, audience, expiry and signature.
// Never accept an access token as a login identity token.Hands-on exercise · reveal the verification check
Draw the authorization code flow and identify each validation.
A token for an unrelated API is rejected.
18 / FIELD NOTE
XSS, trusted rendering and Content Security Policy
Untrusted content must remain inert when added to the DOM. Use textContent or escaped templating for plain text, sanitize deliberately supported HTML and add CSP as defense in depth. Test URLs, attribute contexts and third-party content sources independently.
Imported news and artist data often contain attacker-controlled strings.
Render a headline containing angle brackets in a text node and verify nothing executes.
const title = document.createElement('h2');
title.textContent = untrustedEventTitle;
container.append(title);Hands-on exercise · reveal the verification check
Test hostile event titles in cards, filters and detail views.
Markup is displayed as text without script execution.
19 / FIELD NOTE
Password recovery, rate limits and phishing-resistant authentication
Password storage should use a modern adaptive hash and salt; recovery links need short expiry, single use and non-enumerating responses. Passkeys and MFA options have different resistance to phishing. Protect reset workflows at least as carefully as the login form.
Attackers exploit weak recovery paths after a login mechanism is hardened.
Implement a reset token that is used once and cannot be replayed or printed in application logs.
Hands-on exercise · reveal the verification check
Test token reuse, expiry and enumeration attempts.
Every attack case produces a safe bounded response.
20 / FIELD NOTE
Threat models, secret rotation and verifiable controls
Map actors, assets, data flows, trust boundaries and abuse cases, then connect mitigations to executable tests. Store credentials outside source code, separate environments and grant deployment or agent tools only the scope needed for each operation.
Security checklists are meaningful when attached to a specific design and threat.
Threat-model the public booking form, owner approval screen, email worker and payment webhook as separate boundaries.
// Abuse case: user A requests user B's invoice.
// Expected: server denies even if invoice ID is valid.Hands-on exercise · reveal the verification check
Create six abuse cases and one control for each.
Each control has a concrete test or monitoring signal.