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 (
includeSubDomains flag ensures all subdomains are also covered. The
preload flag allows the domain to be added to browser preload lists, further enforcing HTTPS.
This header prevents browsers from interpreting files as a different MIME type than what is specified. It helps mitigate MIME sniffing attacks.
This header prevents your website from being embedded in an iframe on other sites, protecting against clickjacking attacks.
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.
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.
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.
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.
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.