Advanced Web Security
Master advanced web security: iframe protections, Content Security Policy, cookie security, and CORS.
What is advanced web security?
Advanced web security is the design of explicit trust boundaries around identities, data, browser capabilities, code interpreters, dependencies, and state-changing operations. It assumes that a valid-looking request can still be unauthorized, malicious, stale, cross-site, or unsafe for the context where it will be used.
In plain language, every web request asks the application to trust several claims: who sent it, which object they may touch, what their input means, whether the browser intended the action, and which code may run in the page. Secure systems verify each claim at the boundary that owns the decision.
Core invariant
Treat every value crossing a trust boundary as untrusted until the specific operation validates its shape, authorizes its subject and resource, and safely interprets it. Authentication identifies a caller; it does not grant authority over every record or prove intent for every action.
This lesson assumes basic familiarity with HTTP requests, browser cookies, and database queries. It builds from those foundations into production access control, injection defense, browser policy, session security, dependency integrity, and incident response.
Threat-model assets, actors, and boundaries first
A web threat model names what must be protected, who can influence each input, where trust changes, and what user-visible harm can occur. Start with the application you operate rather than treating a vulnerability list as the architecture.
Who may act?
Identity and authority
Protect sessions, account recovery, tenant membership, privileged roles, service credentials, and every object-level decision. A valid session is only one input to authorization.
What may be seen?
Data and privacy
Protect personal data, business records, secrets, tokens, uploaded files, caches, logs, exports, and backups across their complete lifecycle.
What may execute?
Code and interpretation
Keep untrusted values from becoming SQL, shell syntax, HTML, JavaScript, template expressions, file paths, URLs, or serialized objects.
What must keep working?
Availability and recovery
Protect expensive routes, login and recovery flows, dependencies, queues, and operational access from abuse, exceptional conditions, and cascading failure.
The OWASP Top 10:2025 groups common root causes around broken access control, security misconfiguration, software supply-chain failures, cryptographic failures, injection, insecure design, authentication failures, integrity failures, logging and alerting failures, and mishandled exceptional conditions. Use those categories as review prompts, then trace the concrete paths in your own application.
Inventory the attack surface
- Entry points: routes, forms, APIs, webhooks, WebSockets, uploads, redirects, search fields, templates, and administrative tools.
- Principals: anonymous users, customers, support staff, administrators, background jobs, third parties, and internal services.
- Trust transitions: browser to edge, edge to application, application to data store, one tenant to another, build system to production, and operator to privileged control plane.
- Consequences: disclosure, modification, deletion, account takeover, money movement, code execution, service exhaustion, and loss of evidence needed for recovery.
Put authority checks on the complete request path
A protected route is not the same as a protected operation. The application must carry authenticated identity into a policy decision that includes the exact tenant, resource, action, current business state, and request intent.
A request earns authority one boundary at a time
Each stage narrows what the caller may do. A later service must not infer authority merely because an earlier middleware accepted the request.
Untrusted request
Browser or API client
Supplies route parameters, body fields, headers, cookies, origin context, and potentially attacker-controlled content.
Abuse boundary
Edge controls
Enforce TLS, request-size limits, rate limits, coarse bot controls, and safe parsing before expensive application work.
Authority boundary
Identity and policy
Validate the session, then authorize the action against the loaded resource, tenant, relationship, limits, and current state.
Meaning boundary
Interpreter boundary
Bind database and command parameters, constrain destinations, and encode values for the exact output context where they appear.
Protected consequence
Data or side effect
Read, write, send, spend, or delete only after the operation has independent evidence for identity, authority, input meaning, and intent.
Use the lab to compare a valid session, a generic route guard, and operation-scoped enforcement. Change both the attack path and the posture; the decisive boundary changes with the operation.
Loading request boundaries...
Separate authentication, authorization, and interpretation
These controls answer different questions and must remain independently testable.
Who are you?
Authenticate the principal
Validate the session or token, issuer, audience, expiry, revocation state, and authentication strength. Do not accept algorithms, keys, or identity claims chosen by untrusted input.
May you do this?
Authorize the operation
Check permission and object ownership or tenant membership on every request. Centralize policy logic, but evaluate it with the resource and business state at the point of use.
What does input mean?
Constrain interpretation
Use allowlisted types and ranges, parameterized queries, safe APIs, contextual output encoding, and restricted URL or file destinations. Validation alone does not make string-built code safe.
The executable model keeps object authorization and query binding separate. Change the principal, resource, or bound value to add tests for your own policy.
Match the defense to the interpreter
- SQL and NoSQL queries: use parameter binding or safe query builders; constrain selectable fields and operators separately.
- HTML and DOM output: encode for the destination context and prefer APIs such as
textContent; URL, CSS, attribute, and JavaScript contexts need different handling. - Operating-system commands: avoid a shell when a direct process API works; allowlist executable and argument shapes when execution is necessary.
- Paths and uploads: generate server-side names, normalize and constrain destinations, verify type by content, scan when required, and serve active content from an isolated origin.
- Outbound URLs: parse with a real URL parser, resolve and constrain destinations, block private or metadata networks, and recheck redirects to reduce SSRF risk.
Input sanitization is not a universal transformation that makes a value safe everywhere. Preserve the value as data, validate it for the business operation, and apply the correct control at the interpreter or output context that will consume it.
Treat the browser as a policy-enforcement boundary
The browser automatically carries cookies, isolates origins, renders active content, and decides whether one page may read, execute, or embed another resource. Response headers and cookie attributes narrow those capabilities, but they do not replace server-side authorization.
Execution
Content Security Policy
Use script-src with nonces or hashes to constrain script execution, restrict dangerous resource destinations, and collect violation evidence. Roll out with Report-Only before enforcement when compatibility is uncertain.
Cross-origin reads
CORS
Return an exact allowed origin for trusted browser integrations and opt into credentials deliberately. CORS controls browser access to a response; it is not authentication or authorization for the endpoint.
Ambient identity
Cookie attributes
Use Secure, HttpOnly, a deliberate SameSite mode, narrow path and host scope, rotation, and bounded lifetime. SameSite=None also requires Secure in modern browsers.
Embedding
Frame containment
Send CSP frame-ancestors as a response header to name which ancestors may embed a page. Use 'none' for sensitive surfaces that never need framing.
The policy lab contains both legitimate and hostile flows. A strong configuration must block injected scripts, hostile frames, and forged state changes without silently breaking an approved partner API.
Loading browser policies...
Compose browser controls instead of trusting one header
Browser controls overlap, but each protects a different decision. CSP reduces the impact of injected content; contextual output encoding prevents the injection from becoming active markup. SameSite reduces cross-site cookie delivery; CSRF tokens, Origin checks, or Fetch Metadata provide independent intent evidence. frame-ancestors prevents unwanted embedding; object-level authorization still protects every administrative action.
Deploy the policies deliberately
- CSP: begin with a restrictive target policy in
Content-Security-Policy-Report-Only, remove inline dependencies, classify reports, then enforce. A nonce must be unpredictable and generated per response. - CORS: compare the request origin against an exact server-side allowlist. Never reflect arbitrary origins, and never treat a successful preflight as resource authorization.
- CSRF: keep state changes off safe methods, require a token or equivalent intent check, validate Origin or Fetch Metadata where appropriate, and treat
SameSiteas defense in depth. - Iframes: set
frame-ancestorsin the HTTP response because it is not supported in a CSP meta element and does not inherit fromdefault-src. - Cookies: prefer host-only session cookies with
Secure,HttpOnly, intentionalSameSite, short expiry, rotation after privilege changes, and server-side invalidation.
An origin is scheme, host, and port. A site is based on the registrable domain. SameSite therefore does not provide the same boundary as same-origin policy; sibling subdomains may still be considered same-site.
Design authentication as a lifecycle
Secure login is only the beginning. Registration, verification, session issuance, privilege changes, recovery, revocation, and audit evidence all modify identity authority.
1 Enroll
Establish identity
Verify ownership of the chosen factor, protect registration and recovery from enumeration and abuse, and record the assurance level actually achieved.
2 Authenticate
Issue bounded sessions
Use established identity libraries or providers, memory-hard password hashing, phishing-resistant MFA where risk warrants it, and short-lived, purpose-bound credentials.
3 Authorize
Recheck sensitive actions
Require current policy, object-level checks, transaction limits, and fresh authentication or explicit confirmation for high-consequence operations.
4 Recover
Revoke and investigate
Rotate identifiers after login and privilege changes, revoke sessions on compromise, preserve minimized evidence, notify affected users, and verify recovery from a clean state.
Protect the failure paths
- Rate-limit login, MFA, password reset, invitation, verification, and recovery attempts by multiple signals without creating a trivial account-lockout denial of service.
- Return consistent public responses for account lookup while keeping detailed internal reason codes and correlation IDs.
- Store passwords with a current password-hashing function and calibrated work factor; never encrypt passwords for later recovery.
- Keep session IDs out of URLs and logs, rotate them after authentication or privilege changes, and invalidate server-side state on logout and compromise.
- Require stronger, recent evidence for payout, credential, recovery, permission, and destructive changes than for ordinary reads.
Secure dependencies, configuration, and exceptional paths
Modern web risk includes the code and configuration that enter the product through build and deployment systems. A patched application can still fail through an untrusted package, exposed source map, permissive cloud role, default account, debug route, or exception that fails open.
Provenance
Software supply chain
Pin dependencies, review lockfile changes, verify package and build provenance where available, scan reachable vulnerabilities, protect publishing credentials, and maintain an inventory for urgent response.
Environment
Secure configuration
Start from deny-by-default templates, isolate secrets, disable debug behavior, minimize service permissions, restrict administrative networks, and test the deployed response rather than only source files.
Failure behavior
Exceptional conditions
Define bounded parsing, timeouts, rollback, idempotency, and fail-closed behavior for malformed input, partial writes, dependency timeouts, exhausted resources, and ambiguous outcomes.
Make release evidence reproducible
- Generate a software inventory and attach dependency, secret, static-analysis, and infrastructure-policy results to a versioned build.
- Verify artifacts and configuration between build, staging, and production; do not rebuild an approved release from mutable inputs.
- Test negative cases for unauthorized objects, malformed encodings, oversized bodies, alternate content types, duplicate requests, cross-origin behavior, and dependency failure.
- Remove obsolete routes, packages, flags, credentials, and compatibility exceptions instead of allowing temporary exposure to become permanent.
Detect abuse and recover with evidence
Security logging is useful only when it can trigger a bounded response. Record the decision context needed to investigate without writing passwords, session tokens, authorization headers, full payment data, or unnecessary personal content into logs.
1 Signal
Detect a boundary failure
Alert on denied cross-tenant access, repeated policy failures, impossible session changes, unusual privileged actions, CSP violations, dependency exposure, and rate-limit pressure.
2 Stop
Contain active authority
Revoke affected sessions and credentials, disable the vulnerable operation or dependency path, block confirmed indicators, and preserve unaffected service where possible.
3 Evidence
Reconstruct the effect
Correlate principal, tenant, request, policy decision, object, release, and side-effect IDs; verify what actually changed in the system of record.
4 Recover
Restore with a regression
Patch the failed boundary, remove persistence, rotate exposed secrets, repair data, add the exploit path to automated tests, and restore through a bounded canary.
Instrument decisions, not only errors
- Record authorization outcome, policy version, stable reason code, principal and tenant IDs, resource type, request ID, and release version.
- Separate security evidence from application debug payloads and apply retention, access, integrity, and privacy controls to both.
- Monitor successful high-risk actions as well as denials; account takeover often looks like valid traffic after authentication.
- Test alerts and revocation paths in drills. A dashboard without an owner, threshold, and response action does not contain an incident.
Review the production boundary map
Before release, the team should be able to answer these questions with code, configuration, tests, and runtime evidence:
- Does every operation authenticate the principal and independently authorize the exact tenant, object, action, and current state?
- Can any untrusted value become SQL, shell syntax, HTML, JavaScript, a template expression, a file path, or an outbound URL without a context-specific boundary?
- Do CSP, CORS, cookies, CSRF controls, and
frame-ancestorsmatch the product's real browser integrations in both enforce and failure states? - Are recovery, invitation, MFA, privilege-change, and administrative flows protected as strongly as ordinary login?
- Can the team identify which release contains a vulnerable dependency and revoke its credentials or disable its path quickly?
- Do malformed input, timeouts, duplicate requests, and partial failures preserve authorization and data invariants rather than fail open?
- Can operators correlate a security decision to the principal, policy, object, release, and observed side effect without exposing secrets in logs?
- Has every critical finding become a regression test, a monitored signal, and a rehearsed containment action?
Current primary references for maintaining the design include the OWASP Top 10:2025, the OWASP CSRF Prevention Cheat Sheet, and the W3C Content Security Policy Level 3 specification.