Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 25 min · revision 3

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

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): https vs http
  • Host (domain): example.com vs api.example.com
  • Port: 443 vs 8443

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.

03. Cookies: what the browser sends for you

Cookies are why the gaps in SOP matter. The browser decides whether to attach a cookie by looking at where the request goes, not at which page caused it, within the limits of the cookie's attributes:

  • Secure: sent only over HTTPS, so it cannot leak on a plain HTTP request.
  • HttpOnly: not readable from JavaScript (document.cookie), so an injected script cannot copy the session ID, although it can still send requests that carry it.
  • SameSite: limits cross-site requests. Strict sends the cookie only on requests started from your own site. Lax also sends it on top-level navigations with safe methods, such as following a link, but not on a cross-site form POST, fetch or image. None lets the browser send it on cross-site requests too, where its third-party cookie policy allows, and requires Secure. Chromium-based browsers treat a cookie without the attribute as Lax; other browsers may not, so always set it.
  • Domain and Path: choose which hosts and paths receive the cookie. Without Domain, only the exact host that set it receives it; the __Host- name prefix makes the browser enforce that, together with Secure and Path=/.

Server-side request handling completes the picture. If a handler changes state just because the request carries a valid session cookie, any site the user visits can trigger it: that is Cross-Site Request Forgery (CSRF). SameSite=Lax or Strict stops the cross-site form POST in current browsers. Still check the Origin header or require a CSRF token, because "same-site" includes your other subdomains, and never change state on GET. CORS does not help here: it controls who may read a response, not whether the request is sent. The access control and session lab proves and fixes exactly this flaw.

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 for max-age seconds, 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 short max-age such as 300, raise it to a year once nothing breaks, add includeSubDomains only when every subdomain serves HTTPS (it breaks any that still use plain HTTP), and add preload and submit at hstspreload.org last, because removal from the preload list takes months. The final form is max-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 vague Content-Type, so an uploaded file can be rendered as HTML or run as a script in your origin.

  • X-Frame-Options: DENY (or CSP frame-ancestors 'none'): Stops the page being shown inside an <iframe> on any site, your own included (use SAMEORIGIN or frame-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 the Referer header 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 as geolocation=(), 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-request nonce attribute (<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 as element.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.

Python · ASGI middleware injecting comprehensive security headers
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 response

06. Check your understanding

Practice check · 3 questions

Browser trust, SOP, and security headers

Three questions on Same-Origin Policy, security headers, and CSP nonces.

Q1. Which parts of two URLs must match for the browser to treat them as the same origin?
Q2. Why start HSTS with a short max-age and add preload only as the last step?
Q3. How does a nonce-based Content Security Policy stop injected scripts from running?
Practice only: not graded, not saved, not evidence.

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.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check