Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 80 ยท Web Application Security

HTTP Security Headers

Learn the HTTP security headers that harden every web response: CSP, HSTS, X-Content-Type-Options, frame-ancestors and Referrer-Policy, plus a Python header auditor.

Every HTTP response carries headers, and a handful of them are instructions to the browser about how to treat the page. They don't fix bugs in your code. What they do is shrink the damage when a bug exists: a script injection that would have run freely is blocked, a page that could have been framed by an attacker refuses to load, a request that would have gone over plain HTTP is upgraded.

Security headers are cheap, they work for every page at once, and they are one of the few defenses you can add in a single configuration file. In this lesson you'll learn the headers that matter most, what each value means, and how to write a small auditor that grades a response. They build on earlier lessons: Cross-Site Scripting and Output Encoding introduced Content Security Policy, and CSRF, SameSite and CORS covered cookies and origins.

The headers worth knowing

flowchart LR
    S["Server response<br/>+ security headers"] --> B["Browser enforces policy"]
    B --> A["Blocks inline script<br/>(CSP)"]
    B --> C["Refuses HTTP downgrade<br/>(HSTS)"]
    B --> D["Refuses to be framed<br/>(frame-ancestors)"]
    B --> E["Does not sniff types<br/>(nosniff)"]

The server only sends the rules. The browser is the one that enforces them.

Header Protects against Typical value
Content-Security-Policy XSS, data injection, clickjacking default-src 'self'; frame-ancestors 'none'
Strict-Transport-Security Downgrade to HTTP, cookie theft on plain connections max-age=31536000; includeSubDomains
X-Content-Type-Options MIME sniffing nosniff
Referrer-Policy Leaking full URLs to other sites strict-origin-when-cross-origin
Permissions-Policy Unwanted use of camera, microphone, geolocation camera=(), microphone=(), geolocation=()
Cross-Origin-Opener-Policy Cross-window attacks, some side channels same-origin

You will also see X-Frame-Options (an older way to block framing) and X-XSS-Protection. The second one is obsolete: browsers removed the filter it controlled, and modern advice is to omit it or set it to 0. A good Content-Security-Policy is the real replacement.

Content-Security-Policy

CSP is a list of directives. Each directive names a kind of resource and the sources allowed to supply it. Anything not allowed is blocked, and the browser reports it in the console.

  • default-src 'self' is the fallback for every resource type: only your own origin.
  • script-src controls JavaScript. This is the directive that stops most XSS.
  • style-src, img-src, connect-src (fetch, XHR, WebSocket), font-src, frame-src and form-action restrict the other kinds.
  • object-src 'none' disables legacy plug-ins, and base-uri 'none' stops an injected <base> tag from redirecting your relative URLs.
  • frame-ancestors says who may embed your page in a frame. This is how you prevent clickjacking: frame-ancestors 'none' forbids all framing, 'self' allows only your own pages.

The keywords 'self', 'none' and the others always have single quotes. Without them the browser reads the word as a host name.

The strongest tool against XSS is a policy without 'unsafe-inline' in script-src. Inline <script> blocks and onclick="..." attributes then stop working, so an attacker who injects markup cannot run code. If you do need an inline script, give it a random per-response nonce: the header says script-src 'nonce-R4nd0m' and only <script nonce="R4nd0m"> runs. The nonce must be unpredictable and different on every response, otherwise it is worthless.

Rolling out CSP on an existing site is easier with Content-Security-Policy-Report-Only, which logs violations without blocking anything. Fix what breaks, then switch to enforcing.

Here is a small parser that breaks a policy into directives and flags well-known weaknesses:

Python Reading and judging a CSP

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice how weak still contains 'self'. A policy is only as strong as its most permissive source for a given directive, so one careless addition can undo the rest.

HSTS: never talk plain HTTP again

If a user types bank.example into the address bar, the browser first tries plain HTTP and then follows a redirect to HTTPS. An attacker on the same Wi-Fi can answer that very first request, which is called an SSL-stripping attack. Strict-Transport-Security closes the gap:

TEXT
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload

After the browser sees this once over HTTPS, it refuses plain HTTP for that host for max-age seconds (here one year) and upgrades every request itself. includeSubDomains extends the rule to all subdomains, and preload signals that you want the domain placed in the list built into browsers, which also protects the very first visit. Preloading is hard to undo, so only request it when every subdomain really serves HTTPS. The header is ignored when it arrives over plain HTTP, since an attacker could forge it there. Certificates are explained in TLS, Certificates and PKI.

The small but important ones

X-Content-Type-Options: nosniff tells the browser to trust the Content-Type you sent. Without it, a browser may "sniff" a user-uploaded text file and decide it is HTML or JavaScript, which turns an upload feature into an XSS hole. Always send correct content types and this header.

Referrer-Policy controls how much of the previous URL is sent in the Referer header when a user follows a link. URLs sometimes contain reset tokens or search terms. strict-origin-when-cross-origin sends the full URL within your own site, only the origin to other HTTPS sites, and nothing on a downgrade to HTTP. For sensitive pages use no-referrer.

Permissions-Policy switches off browser features you do not use, so a compromised script or embedded frame cannot ask for the camera or location.

Cookie attributes belong to the same family: Secure, HttpOnly and SameSite are set on Set-Cookie, and you saw them in Sessions, Cookies and JWTs.

Information leaks: headers such as Server: Apache/2.4.1 or X-Powered-By: PHP/8.4 tell attackers which versions to look for. Hiding them is not a real defense, but it costs nothing.

Setting the headers

The mechanism depends on your stack, but the idea is the same everywhere: add them in one central place so no page is forgotten. In nginx it looks like this (read-only, as the sandbox here has no web server):

NGINX
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self'; frame-ancestors 'none'" always;

The always flag makes nginx send them on error pages too. Frameworks usually offer middleware for the same job, and Python web frameworks can set the headers in a response hook.

A header auditor

Checking by eye does not scale. Here is a function that grades a response (as a dictionary) against a short list of rules and produces a score. It uses three fake responses, one for each kind of site you meet in practice.

Python Audit sample responses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A score is a conversation starter, not a certificate. Online scanners use similar logic, but they cannot tell whether your CSP actually blocks the attack you care about. Testing real behavior in a browser, with the report-only mode first, is what proves it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which header should you use to stop other sites from embedding your page in a frame?

    frame-ancestors lists the origins allowed to embed the page, so 'none' prevents clickjacking via frames. The older X-Frame-Options header does the same job in a less flexible way.
  2. 2. A policy says script-src 'self' 'unsafe-inline'. What is the main problem?

    'unsafe-inline' allows inline script blocks and event-handler attributes, which is exactly what an XSS payload uses. A nonce-based or external-script-only policy is much stronger.
  3. 3. What does Strict-Transport-Security do after the browser has seen it over HTTPS?

    The browser remembers the host for max-age seconds and upgrades requests itself, which removes the plain-HTTP first request that SSL-stripping attacks rely on.
  4. 4. Why send X-Content-Type-Options: nosniff?

    Without it a browser may treat an uploaded text or image file as HTML or script. With nosniff it trusts the Content-Type header.
  5. 5. What is the safest way to introduce a new CSP on a large existing site?

    Report-only mode logs what would have been blocked without breaking pages, so you can adjust the policy before it is enforced.

Summary

  • Security headers are instructions the browser enforces; they limit the damage of bugs but do not replace secure code.
  • CSP controls which resources may load; avoid 'unsafe-inline' and wildcards in script-src, use nonces when inline code is unavoidable, and set frame-ancestors against clickjacking.
  • HSTS forces HTTPS for a host for a set time; only preload when every subdomain supports HTTPS.
  • nosniff, a strict Referrer-Policy and Permissions-Policy are one-line wins.
  • Set headers centrally, roll out CSP with report-only mode first, and audit responses automatically.

Next: API Security, where you'll protect the endpoints that apps and scripts call.