Lesson 9 of 11
Security Headers Implementation
Security headers are HTTP response headers that instruct browsers how to behave when handling your application's content. They provide significant protection against XSS, clickjacking, MIME sniffing, and downgrade attacks - and take minutes to implement.
Essential Security Headers
# Complete security headers implementation - Python Flask
from flask import Flask
app = Flask(__name__)
@app.after_request
def add_security_headers(response):
# HSTS - Force HTTPS for 1 year, all subdomains, submit for browser preload list
response.headers['Strict-Transport-Security'] = (
'max-age=31536000; includeSubDomains; preload'
)
# CSP - Control which resources can be loaded
response.headers['Content-Security-Policy'] = (
"default-src 'self'; " # Only load from same origin by default
"script-src 'self' https://cdn.example.com; " # Scripts: self + trusted CDN
"style-src 'self' 'unsafe-inline'; " # Styles from self (inline allowed)
"img-src 'self' data: https:; " # Images from anywhere over HTTPS
"font-src 'self' https://fonts.gstatic.com; "
"connect-src 'self' https://api.example.com; " # AJAX/Fetch to self + API
"frame-ancestors 'none'; " # = X-Frame-Options: DENY (no iframes)
"object-src 'none'; " # No Flash, Java applets
"base-uri 'self'; " # Prevent base tag injection
"form-action 'self'; " # Forms can only submit to self
"upgrade-insecure-requests" # Force HTTPS for all page resources
)
# Prevent clickjacking (legacy support alongside CSP frame-ancestors)
response.headers['X-Frame-Options'] = 'DENY'
# Prevent MIME type sniffing
response.headers['X-Content-Type-Options'] = 'nosniff'
# Control referrer information sent to third parties
response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
# Restrict browser feature access
response.headers['Permissions-Policy'] = (
'camera=(), microphone=(), geolocation=(), '
'payment=(), usb=(), bluetooth=()'
)
# Remove server information
response.headers.pop('Server', None)
response.headers.pop('X-Powered-By', None)
return responseContent Security Policy Deep Dive
- CSP Report-Only mode: Start with Content-Security-Policy-Report-Only to monitor violations without blocking - identifies what you'd break before enforcement
- CSP nonces: For inline scripts that cannot be moved to external files, use a per-request nonce: <script nonce='abc123'>. CSP header: script-src 'nonce-abc123'
- CSP hashes: For trusted inline scripts, hash them: script-src 'sha256-[base64-hash]'. Any modification invalidates the hash
- Testing: Use Mozilla Observatory (observatory.mozilla.org) and Google CSP Evaluator to test your headers. Aim for A+ grade
- Strict CSP (Google recommendation): script-src 'nonce-{random}' 'strict-dynamic' - eliminates whitelist bypasses while allowing dynamic script loading
Common Mistakes
- CSP with 'unsafe-inline' for scripts - defeats the entire purpose of CSP for XSS protection; use nonces or hashes instead
- Setting X-Frame-Options on API responses - X-Frame-Options only applies to pages loaded in browsers; API responses don't need it but do need CORS headers
- HSTS without testing HTTPS first - if you set HSTS and HTTPS breaks, users are locked out of your site for the max-age duration; test HTTPS thoroughly before enabling HSTS preload
Live Security Headers & SSL Audit
Tip
Test your live web application's HTTP response headers and SSL cipher suites in seconds using WeSecureX Free Security Scanner. You will get an instant security grade (A+ through F) alongside recommended Nginx, Apache, and Next.js header snippets to resolve missing directives.
The foundational security model: Confidentiality (privacy), Integrity (trust), and Availability (uptime).
Tip
Tip
Practice Security Headers Implementation in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Practice Task
Note
Practice Task - (1) Write a working example of Security Headers Implementation from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Security Headers Implementation is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cybersecurity code.
Key Takeaways
- Security headers are HTTP response headers that instruct browsers how to behave when handling your application's content.
- CSP Report-Only mode: Start with Content-Security-Policy-Report-Only to monitor violations without blocking - identifies what you'd break before enforcement
- CSP nonces: For inline scripts that cannot be moved to external files, use a per-request nonce: <script nonce='abc123'>. CSP header: script-src 'nonce-abc123'
- CSP hashes: For trusted inline scripts, hash them: script-src 'sha256-[base64-hash]'. Any modification invalidates the hash
Finished this lesson?