Response Headers
Introduction
Response headers play a critical role in web security and functionality by providing essential instructions from the server to the client's browser. They dictate how the browser should handle the response, enforce security policies, manage caching behaviors, and control access to resources. For instance, headers can enforce the use of secure connections, prevent code injection attacks, control resource sharing between different origins, and restrict the usage of certain browser features. By appropriately configuring response headers, developers can significantly enhance the security posture of a web application, protect sensitive data from unauthorized access, and ensure that the application behaves consistently and safely across different user environments. These headers are a fundamental aspect of securing web applications and maintaining their integrity and performance.
Response Headers
Content-Security-Policy (CSP)
Purpose: Helps prevent various types of attacks, such as Cross-Site Scripting (XSS), Clickjacking, and other code injection attacks by specifying the sources from which content can be loaded. When to Use: Apply CSP when you need to restrict the sources of content like scripts, images, and styles to trusted domains. It's crucial for applications handling sensitive data or complex client-side logic. Example Value: default-src 'self'; img-src https://trusted.example.com; script-src 'self' 'unsafe-inline';
Explanation: This policy allows content only from the site's own origin ('self'
), images from https://trusted.example.com
, and scripts from the site's own origin, allowing inline scripts.
Strict-Transport-Security (HSTS)
Purpose: Enforces secure (HTTP over SSL/TLS) connections to the server, preventing man-in-the-middle attacks and cookie hijacking. When to Use: Implement HSTS on any website accessible over HTTPS to ensure all future requests are made over secure channels. Example Value: max-age=31536000; includeSubDomains
Explanation: This instructs the browser to only communicate with the site over HTTPS for one year and includes all subdomains.
X-Content-Type-Options
Purpose: Prevents browsers from MIME-sniffing a response away from the declared content-type, reducing the risk of drive-by downloads and similar attacks. When to Use: Always use this header to enforce the correct MIME type, especially when serving files that could be interpreted incorrectly by browsers. Example Value: nosniff
Explanation: This forces browsers to respect the MIME type declared in the Content-Type header.
X-Frame-Options
Purpose: Protects against Clickjacking attacks by controlling whether a browser should be allowed to render a page in a <frame>
, <iframe>
, <embed>
, or <object>
. When to Use: Apply this header to pages that should not be embedded in frames or iframes, particularly login pages and sensitive transaction pages. Example Value: DENY
Explanation: This completely prevents the page from being framed.
X-XSS-Protection
Purpose: Enables the Cross-site scripting (XSS) filter built into most recent web browsers. It's a quick fix to prevent XSS attacks. When to Use: Use this header as an additional layer of defense against XSS, although relying solely on it is not recommended. Example Value: 1; mode=block
Explanation: This enables the XSS filter and instructs the browser to block the page if an attack is detected.
Referrer-Policy
Purpose: Controls how much referrer information (sent via the Referer header) should be included with requests, helping reduce leakage of sensitive information. When to Use: Use this header to protect sensitive referrer information, especially when navigating between secure and non-secure pages. Example Value: no-referrer
Explanation: This ensures that no referrer information is sent along with requests.
Permissions-Policy
Purpose: Controls which web platform features and APIs can be used in the web application, enabling or disabling features like geolocation, camera, microphone, etc. When to Use: Use this header to restrict the use of potentially risky features in your web application. Example Value: geolocation=(), camera=()
Explanation: This disables the use of geolocation and camera features.
Cache-Control
Purpose: Directives for caching mechanisms in both requests and responses. Proper cache control can prevent sensitive information from being stored in caches. When to Use: Implement this header to manage caching behavior, particularly for sensitive data that should not be stored in caches. Example Value: no-store, no-cache, must-revalidate, proxy-revalidate
Explanation: This ensures that the response is not stored in any caches and must be validated with the server before being used.
Expect-CT
Purpose: Allows sites to opt into reporting and/or enforcement of Certificate Transparency requirements, protecting against the use of misissued certificates. When to Use: Use this header to ensure that only certificates logged in public CT logs are trusted by the browser. Example Value: max-age=86400, enforce, report-uri="https://example.com/report"
Explanation: This instructs the browser to enforce Certificate Transparency for one day and to report any violations to the specified URI.
Feature-Policy
Purpose: Provides control over the usage of various browser features and APIs to avoid potential misuse that could lead to security vulnerabilities. When to Use: Similar to Permissions-Policy, use this to limit the use of browser features to enhance security. Example Value: geolocation 'self'; vibrate 'none'
Explanation: This restricts the use of geolocation to the site's own origin and disables the vibrate feature.
Cross-Origin Resource Policy (CORP)
Purpose: Helps mitigate speculative execution side-channel attacks and cross-origin information leaks by controlling which origins can read the resources. When to Use: Use this header to restrict which origins can access your resources, enhancing security for sensitive information. Example Value: same-origin
Explanation: This ensures that resources can only be accessed by the same origin.
Cross-Origin Opener Policy (COOP)
Purpose: Ensures a top-level document does not share a browsing context group with cross-origin documents, isolating documents from other origins for better security. When to Use: Apply this header to isolate your site from other potentially malicious origins, preventing them from interacting with your site's context. Example Value: same-origin
Explanation: This ensures that the top-level document does not share a browsing context group with any cross-origin documents.
Cross-Origin Embedder Policy (COEP)
Purpose: Ensures that a document can only load resources from the same origin or resources explicitly marked as loadable from other origins, preventing cross-origin data leaks. When to Use: Use this header to control cross-origin resource loading, ensuring only safe resources are embedded. Example Value: require-corp
Explanation: This ensures that a document can only load resources from the same origin or resources explicitly marked as loadable from other origins.
Access-Control-Allow-Origin
Purpose: Part of CORS (Cross-Origin Resource Sharing), it specifies which origins are permitted to read responses from the server, preventing unauthorized web clients from accessing sensitive data. When to Use: Apply this header when you need to allow cross-origin requests from trusted domains. Example Value: https://trusted.example.com
Explanation: This allows requests from https://trusted.example.com
to access the resources.
Public-Key-Pins (HPKP)
Purpose: Allows websites to declare which public keys browsers should trust during certificate validation, preventing man-in-the-middle attacks with rogue certificates. When to Use: Use cautiously, as misconfiguration can lock out users. Ideal for high-security environments. Example Value: pin-sha256="base64+primary=="; pin-sha256="base64+backup=="; max-age=5184000; includeSubDomains
Explanation: This pins the specified public keys for certificate validation, ensuring only certificates with these keys are trusted.
Expect-Staple
Purpose: Signals that the server expects OCSP Stapling to be used, ensuring the validity of the SSL certificate in use. When to Use: Use this to ensure clients receive timely and valid certificate status information. Example Value: max-age=3600, enforce, report-uri="https://example.com/report"
Explanation: This expects the use of OCSP Stapling and reports violations to the specified URI.
X-Download-Options
Purpose: Prevents Internet Explorer from opening downloaded files automatically, reducing the risk of drive-by downloads and execution of malicious files. When to Use: Apply this header to prevent automatic execution of downloaded files in Internet Explorer. Example Value: noopen
Explanation: This instructs Internet Explorer not to open files automatically after downloading.
X-Permitted-Cross-Domain-Policies
Purpose: Restricts Adobe Flash and Acrobat from loading content on your site, preventing certain types of cross-domain attacks. When to Use: Use this header if your site does not use Flash or Acrobat content to prevent unnecessary exposure. Example Value: none
Explanation: This prevents Flash and Acrobat from loading content on your site.
X-DNS-Prefetch-Control
Purpose: Controls DNS prefetching, reducing the risk of DNS-based attacks and improving privacy. When to Use: Use this header to manage DNS prefetching behavior for better security and privacy. Example Value: off
Explanation: This disables DNS prefetching to prevent DNS-based attacks and improve privacy.
Server
Purpose: Omitting or customizing this header can prevent attackers from identifying the server software, mitigating certain targeted attacks. When to Use: Use this header to obfuscate server details, reducing the risk of targeted attacks based on server software. Example Value: `` Explanation: Omitting or customizing the Server header prevents attackers from identifying the server software.
Set-Cookie with Secure and HttpOnly flags
Purpose: Ensures cookies are only sent over secure connections and are inaccessible to JavaScript, reducing the risk of cookie theft and Cross-Site Scripting (XSS) attacks. When to Use: Always use these flags for sensitive cookies, such as session tokens. Example Value: sessionid=abc123; Secure; HttpOnly
Explanation: This sets a cookie that is only sent over HTTPS and is not accessible via JavaScript.
Clear-Site-Data
Purpose: Allows web applications to clear browsing data (cookies, storage, cache) to ensure that sensitive data is not accessible to malicious actors. When to Use: Use this header to clear site data after sensitive actions or user logouts. Example Value: "cache", "cookies", "storage", "executionContexts"
Explanation: This clears the specified types of site data.
Pragma
Purpose: Includes implementation-specific directives that might apply to any recipient along the request/response chain. When used with "no-cache," it prevents sensitive data from being cached. When to Use: Use this header to control caching behavior for sensitive data, similar to Cache-Control. Example Value: no-cache
Explanation: This prevents the response from being cached.
X-Frame-Options: ALLOW-FROM
Purpose: While DENY and SAMEORIGIN are most commonly used, ALLOW-FROM allows framing from a specific origin, useful for controlling framing in a more granular way. When to Use: Use this header if you need to allow framing from specific trusted origins only. Example Value: ALLOW-FROM https://trusted.example.com
Explanation: This allows the page to be framed only from the specified origin.
NEL (Network Error Logging)
Purpose: Allows websites to receive reports about network errors that occur when the site is accessed by a user, useful for detecting and mitigating network issues or attacks. When to Use: Use this header to monitor and respond to network errors, enhancing overall security and reliability. Example Value: {"report_to":"default","max_age":31536000,"include_subdomains":true,"failure_fraction":0.1}
Explanation: This enables network error logging and reports errors to the specified endpoint.
Content-DPR
Purpose: Specifies the ratio between the physical pixels on the user's device and the device-independent pixels of the layout viewport, helping to mitigate certain image-based attacks. When to Use: Use this header to control how images are served based on device characteristics. Example Value: 1.5
Explanation: This sets the device pixel ratio to 1.5.
Content-Language
Purpose: Ensures correct language settings, preventing certain types of phishing attacks. When to Use: Always use this header to specify the language of your content, improving localization and security. Example Value: en-US
Explanation: This sets the language of the content to English (United States).
Vary
Purpose: Instructs caches to store multiple versions of a response based on specified header fields, useful for preventing cache poisoning attacks. When to Use: Use this header to ensure proper caching behavior, particularly when serving varied content based on headers like User-Agent. Example Value: Accept-Encoding
Explanation: This instructs caches to store different versions of the response based on the Accept-Encoding
header.
Alt-Svc (Alternative Services)
Purpose: Indicates that an origin can be reached using a different network location (host, port, protocol), improving performance and security by specifying secure alternatives. When to Use: Use this header to specify alternative services for your site, enhancing performance and security. Example Value: h2="example.com:443"; ma=2592000
Explanation: This specifies an alternative service (h2
) available at example.com
on port 443, with a max age of 30 days.
Content-Disposition
Purpose: Suggests a filename for the "Save As" dialog box and instructs the browser on how to handle file downloads, preventing certain types of attacks related to file downloads. When to Use: Use this header to control how files are downloaded and handled by the browser, ensuring security. Example Value: attachment; filename="filename.jpg"
Explanation: This instructs the browser to handle the content as an attachment and suggests a filename for the download.
Last updated