TL;DR
Checking HTTP headers like Origin and Referer can help mitigate Cross-Site Request Forgery (CSRF) attacks, but it’s not a foolproof solution on its own. It’s best used as an *additional* layer of defence alongside proper CSRF tokens.
What is CSRF?
Cross-Site Request Forgery (CSRF) lets attackers trick users into performing actions they didn’t intend to, usually on websites where they are already logged in. Imagine you’re logged into your bank and an attacker gets you to click a malicious link – that link could make changes to your account without your knowledge.
How HTTP Headers Help
HTTP headers contain information about the request being sent from the browser to the server. We can use specific headers to verify if the request originated from our own website.
Steps to Implement Header-Based CSRF Protection
- Understand the Relevant Headers:
Origin: This header indicates the server that initiated the request. It’s generally considered more reliable thanReferer.Referer: This header tells you which page the user came from. It can be spoofed or missing, so it’s less trustworthy.- Server-Side Validation (Example using Python/Flask):
- Check for Missing Headers:
- Consider Browser Compatibility:
- Not all browsers send the
Originheader consistently. Older browsers might not support it at all. - The
Refererheader can be stripped by privacy settings or browser extensions. - Use with CSRF Tokens:
from flask import Flask, request, redirect, url_for
app = Flask(__name__)
@app.route('/sensitive-action', methods=['POST'])
def sensitive_action():
if request.origin != 'https://yourwebsite.com':
return "Invalid Origin!", 403 #Forbidden
# ... process the action safely...
return redirect(url_for('home'))
In this example, we check if the Origin header matches our website’s domain. If it doesn’t, we reject the request.
If either Origin or Referer is missing, treat the request with suspicion. Some browsers don’t send these headers in all cases.
Crucially, don’t rely on HTTP headers alone! Always use proper CSRF tokens as your primary defence mechanism. Headers provide an extra layer of security but shouldn’t be the only protection.
Limitations
- Spoofing: The
Refererheader is easily spoofed by attackers. - Browser Inconsistencies: Different browsers handle these headers differently.
- Subdomain Issues: Requests from subdomains might pass the origin check even if they shouldn’t.
Conclusion
Checking HTTP headers can be a useful addition to your CSRF protection strategy, but it’s not a replacement for proper CSRF tokens. Implement both for robust security.

