Why should I set the headers mentioned in this article?
By setting these headers, web developers can implement a defense-in-depth approach to secure their applications. These headers complement other security measures like input validation, authentication, and authorization, providing an extra layer of protection against various attack vectors.
Let’s take a look at the various headers.
1. Strict-Transport-Security (HSTS)
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
HSTS instructs the browser to only access the site over HTTPS for a specified duration (max-age
). The includeSubDomains
flag ensures all subdomains are also covered. The preload
flag allows the domain to be added to browser preload lists, further enforcing HTTPS.
2. X-Content-Type-Options
X-Content-Type-Options: nosniff
This header prevents browsers from interpreting files as a different MIME type than what is specified. It helps mitigate MIME sniffing attacks.
3. X-Frame-Options
X-Frame-Options: DENY
This header prevents your website from being embedded in an iframe on other sites, protecting against clickjacking attacks.
4. X-XSS-Protection
X-XSS-Protection: 1; mode=block
5. Content-Security-Policy (CSP)
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; object-src 'none'
CSP helps prevent various types of attacks, like XSS and data injection, by specifying the allowed sources for scripts, styles, images, and other resources.
6. Referrer-Policy
Referrer-Policy: no-referrer, strict-origin-when-cross-origin
This header controls what information is sent as the Referer
header when navigating to another page. It can help protect sensitive information.
7. Content-Type
Content-Type: text/html; charset=utf-8
Setting the correct Content-Type
header ensures browsers interpret the content correctly, reducing the risk of content-based attacks.
8. Cache-Control
Cache-Control: no-store, no-cache, must-revalidate, proxy-revalidate
This header prevents caching of sensitive data and ensures that browsers revalidate the content with the server before displaying it.
9. X-Permitted-Cross-Domain-Policies
X-Permitted-Cross-Domain-Policies: none
This header restricts Adobe Flash Player from making cross-domain requests, protecting against certain attacks.
10. Feature-Policy (optional)
Feature-Policy: camera 'none'; microphone 'none'; geolocation 'none'; payment 'none'
This header controls the availability of certain browser features on your website, reducing the risk of unauthorized access.
Keep in mind that the actual headers you need to set may vary depending on the specific requirements and technologies used in your web application. Always test thoroughly to ensure that these headers do not cause any compatibility issues with your application. Especially the ‘Content-Security-Policy’ header is one that requires special attention, because it’s prone to breaking parts of your application.