Testing and Validating Security Headers

Testing and Validating Security Headers

Proper testing ensures your security headers work as intended without breaking functionality:

# Test headers using curl
curl -I https://example.com
curl -I -H "Origin: https://trusted-domain.com" https://example.com

# Test specific security headers
curl -s -D- https://example.com -o /dev/null | grep -i strict-transport-security
curl -s -D- https://example.com -o /dev/null | grep -i content-security-policy

# Test CORS preflight
curl -H "Origin: https://trusted-domain.com" \
     -H "Access-Control-Request-Method: POST" \
     -H "Access-Control-Request-Headers: X-Requested-With" \
     -X OPTIONS \
     https://example.com/api/endpoint

Create automated tests for security headers:

#!/usr/bin/env python3
import requests

def test_security_headers(url):
    response = requests.get(url)
    headers = response.headers
    
    required_headers = {
        'Strict-Transport-Security': 'max-age=',
        'X-Content-Type-Options': 'nosniff',
        'X-Frame-Options': ['SAMEORIGIN', 'DENY'],
        'X-XSS-Protection': '1; mode=block',
        'Content-Security-Policy': 'default-src'
    }
    
    for header, expected in required_headers.items():
        if header in headers:
            if isinstance(expected, list):
                if not any(exp in headers[header] for exp in expected):
                    print(f"⚠️  {header}: {headers[header]} (expected one of: {expected})")
            elif expected not in headers[header]:
                print(f"⚠️  {header}: {headers[header]} (expected to contain: {expected})")
            else:
                print(f"✓ {header}: {headers[header]}")
        else:
            print(f"✗ {header}: Missing")

test_security_headers('https://example.com')