Browser Trust and Client-Side Hardening
Understand the browser Same-Origin Policy, enforce a Content Security Policy with nonces and Trusted Types, and send the HTTP security response headers that close common client-side attack paths.
Contentsand lesson path
On this page
- Why it matters
- The Same-Origin Policy and CORS fundamentals
- Cookies: what the browser sends for you
- Essential HTTP security response headers
- Content Security Policy (CSP) with nonces and Trusted Types
- Check your understanding
- Apply it
- Review prompt
Lessons of Web Application Security
- Browser Trust and Client-Side Hardening Concept · 25 min
- Injection, Traversal, XSS and SSRF: Root Causes and Fixes Worked example · 30 min
- Testing a Practice App Through an Intercepting Proxy Lab · 30 min
- Finding and Fixing Access Control, API and Session Flaws Lab · 30 min
- Findings, Fixes and Interim WAF Mitigations Worked example · 25 min
- Web Application Security Check Knowledge check · 10 questions
What you will learn
- Explain how the browser security model (same-origin policy, cookies, CORS) and server-side request handling create the conditions for common web vulnerabilities.
- Harden the client side of a web application: sanitise untrusted rich content (Markdown, LLM output) before it reaches framework escape hatches such as dangerouslySetInnerHTML, enforce CSP with Trusted Types, load third-party scripts with Subresource Integrity, and enforce HTTPS with HSTS and no mixed content.
01. Why it matters
A user's browser runs your JavaScript, but it also runs pages from every other site the user visits, some of them hostile, and it attaches your cookies to requests that those pages trigger. Browsers keep sites apart with the Same-Origin Policy (SOP), but that rule leaves gaps, and many common attacks work through them.
For example, if an attacker slips one <script> tag into a page on your site, the browser runs it as if it were your own code. That script can read what the user sees and send requests in the user's name, such as a money transfer.
The backend controls much of this. Cookie attributes decide when the browser sends your session along, response headers tell the browser what it may load, run or frame, and a Content Security Policy (CSP) limits which scripts run at all.
02. The Same-Origin Policy and CORS fundamentals
The Same-Origin Policy (SOP) is the cornerstone of web application security. Two URLs have the same origin if and only if they share three identical tuple elements:
- Scheme (protocol):
httpsvshttp - Host (domain):
example.comvsapi.example.com - Port:
443vs8443
Under SOP, a script executing on https://bank.example.com cannot read the Document Object Model (DOM), local storage, or XMLHttpRequest/fetch responses belonging to https://evil.example.com.
However, developers frequently misunderstand what SOP does NOT restrict:
- SOP allows cross-origin embedding: Web pages can freely embed cross-origin images (
<img>), stylesheets (<link>), iframes (<iframe>), and executable scripts (<script>). If a content delivery network (CDN) serving your scripts is compromised, SOP will not prevent the malicious CDN script from executing in your origin! - SOP allows cross-origin writes: By default, HTML forms and image beacons can issue cross-origin POST or GET requests to other origins, forming the basis of Cross-Site Request Forgery (CSRF).
Furthermore, engineers must understand Cross-Origin Resource Sharing (CORS). CORS is not a server-side security feature; rather, it is a relaxation mechanism that allows servers to instruct browsers to permit cross-origin reads for specific origins. A dangerous anti-pattern is dynamically reflecting the incoming Origin header into Access-Control-Allow-Origin: <origin> with Access-Control-Allow-Credentials: true. This effectively disables SOP, allowing any malicious website to read authenticated user data through cross-origin fetch calls.
04. Essential HTTP security response headers
A small set of response headers turns on browser protections that are off by default. Send them from every web application and API:
-
Strict-Transport-Security(HSTS): Tells browsers to use only HTTPS for your domain formax-ageseconds, which defeats SSL-stripping attacks on later visits. It cannot protect the very first visit (or the first after it expires) unless the domain is on the browsers' built-in preload list. Roll it out in stages: start with a shortmax-agesuch as 300, raise it to a year once nothing breaks, addincludeSubDomainsonly when every subdomain serves HTTPS (it breaks any that still use plain HTTP), and addpreloadand submit at hstspreload.org last, because removal from the preload list takes months. The final form ismax-age=63072000; includeSubDomains; preload. -
X-Content-Type-Options: nosniff: Stops the browser guessing a response's type from its bytes (MIME sniffing), and makes it refuse script and style loads whose declared type does not match. Without it, a browser may guess the type of an upload served with a missing or vagueContent-Type, so an uploaded file can be rendered as HTML or run as a script in your origin. -
X-Frame-Options: DENY(or CSPframe-ancestors 'none'): Stops the page being shown inside an<iframe>on any site, your own included (useSAMEORIGINorframe-ancestors 'self'if your own pages frame it). That stops clickjacking, where an attacker frames your page invisibly under a decoy button. -
Referrer-Policy: strict-origin-when-cross-origin: Sends only the origin, not the path or query string, in theRefererheader of cross-origin requests, so secrets in URLs (such as password reset tokens) do not leak to other sites. It is also the default in current browsers; sending it explicitly protects users of older ones. -
Permissions-Policy: Turns off browser features the page does not use, such asgeolocation=(), camera=(), microphone=(), payment=().
One related protection is not a header but an HTML attribute. Subresource Integrity (SRI) puts the expected hash of a third-party script in the tag that loads it (integrity="sha384-..." crossorigin="anonymous"). The browser hashes the downloaded file and refuses to run it if even one byte differs, for example because the CDN was compromised.
05. Content Security Policy (CSP) with nonces and Trusted Types
Content Security Policy (CSP) is a strong second layer of defence against Cross-Site Scripting (XSS) and data exfiltration, behind correct output encoding. CSP is delivered via the Content-Security-Policy HTTP header. Rather than relying on domain allowlists (which can often be bypassed via JSONP endpoints or CDN gadget scripts), modern CSP relies on cryptographic nonces and Trusted Types.
A strict, nonce-based policy looks like this:
Content-Security-Policy: default-src 'none'; script-src 'nonce-R4nd0mStr1ng' 'strict-dynamic'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; require-trusted-types-for 'script';
The middleware below sends exactly this policy with a fresh nonce on each response. If your pages call an API on another origin, add it to connect-src (for example connect-src 'self' https://api.example.com). The key directives:
-
default-src 'none': Implements default-deny. Any resource type not explicitly allowed is blocked by the browser engine. -
script-src 'nonce-...': Only scripts bearing the exact matching per-requestnonceattribute (<script nonce="...">) are executed. Injected scripts from attackers lack the secret random nonce and are instantly rejected. -
require-trusted-types-for 'script': In browsers that support Trusted Types, makes dangerous sinks (such aselement.innerHTML) refuse plain strings, so only values created by an audited Trusted Types policy (for example one that sanitises with DOMPurify) reach them. Browsers without support ignore the directive, so it is an extra layer, not the only one.
By pairing dynamic nonces with strict-dynamic, modern browsers allow legitimate scripts loaded with a valid nonce to dynamically load subsequent application bundles without requiring extensive domain allowlisting.
import secrets
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response
# Roll HSTS out in stages: start with a short max-age, raise it, add
# includeSubDomains once every subdomain serves HTTPS, and add preload
# (then submit at hstspreload.org) only as the last, hard-to-undo step.
HSTS_POLICY = "max-age=300"
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
"""Injects defensive HTTP headers and per-request CSP nonces."""
async def dispatch(self, request: Request, call_next) -> Response:
# Generate unpredictable 128-bit base64 nonce for CSP
csp_nonce = secrets.token_urlsafe(16)
request.state.csp_nonce = csp_nonce
response: Response = await call_next(request)
# Construct hardened Content Security Policy
csp_policy = (
"default-src 'none'; "
f"script-src 'nonce-{csp_nonce}' 'strict-dynamic'; "
"style-src 'self'; "
"img-src 'self' data:; "
"font-src 'self'; "
"connect-src 'self'; "
"base-uri 'none'; "
"frame-ancestors 'none'; "
"require-trusted-types-for 'script';"
)
headers = response.headers
headers["Content-Security-Policy"] = csp_policy
headers["Strict-Transport-Security"] = HSTS_POLICY
headers["X-Content-Type-Options"] = "nosniff"
headers["X-Frame-Options"] = "DENY"
headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
headers["Permissions-Policy"] = (
"geolocation=(), camera=(), microphone=(), payment=()"
)
return response06. Check your understanding
07. Apply it
Audit your application's response headers using tools like curl -I or the Mozilla Observatory. Implement the SecurityHeadersMiddleware demonstrated in this lesson to inject HSTS, X-Content-Type-Options: nosniff, X-Frame-Options: DENY, Referrer-Policy, and a nonce-based CSP.
When rolling out Content Security Policy across existing legacy codebases, begin by deploying Content-Security-Policy-Report-Only with a configured report-uri or report-to endpoint. This allows you to monitor and collect telemetry on legitimate inline scripts, third-party analytics widgets, and potential violations in your staging environment without breaking production user flows. Once all legitimate assets include nonces or hashes, switch the header to active enforcement.
These headers do not fix injection bugs, but they make many client-side attacks fail or much harder to exploit. In the next lesson, you will analyse the mechanics and root causes of server-side injection flaws: SQL Injection, Path Traversal, XSS, and SSRF.
08. Review prompt
Explain the three components of the Same-Origin Policy and identify two cross-origin capabilities that SOP permits by default. Explain which cookie attributes keep another site's form from using your session, and why a CSRF check is still needed. Describe how X-Content-Type-Options: nosniff prevents MIME-confusion attacks, explain the critical security risks of dynamically reflecting client Origin in CORS headers, and explain, step by step, how a nonce-based Content Security Policy stops injected scripts.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.