Setting the HttpOnly attribute on cookies prevents client-side scripts from reading their values, limiting the damage that cross-site
scripting (XSS) attacks can cause.
Why is this an issue?
When a cookie is created without the HttpOnly attribute, or with it explicitly set to false, client-side scripts running
in the browser can read the cookie’s value. By default, cookies are created with HttpOnly set to false, meaning they are
accessible to browser scripts unless the developer explicitly enables this protection. Setting HttpOnly to true instructs
the browser to block script access to the cookie, limiting the damage from XSS attacks that attempt to steal session credentials.
What is the potential impact?
Session hijacking and account takeover
The most common target of cookie theft is the session cookie used to authenticate a user. If an attacker can exploit an XSS vulnerability on a page where a session cookie is accessible to scripts, they can steal it and use it to impersonate the authenticated user without needing their credentials. This can lead to unauthorized access to sensitive account data, account takeover, and potential privilege escalation within the application.
How to fix it
Code examples
The following code creates a cookie without enabling the HttpOnly attribute.
Noncompliant code example
HttpCookie myCookie = new HttpCookie("Sensitive cookie");
myCookie.HttpOnly = false; // Noncompliant: this cookie is created with the httponly flag set to false and so it can be stolen easily in case of XSS vulnerability
Compliant solution
HttpCookie myCookie = new HttpCookie("Sensitive cookie");
myCookie.HttpOnly = true;
Resources
Documentation
Standards
- OWASP - Top 10 2021 Category A5 - Security Misconfiguration
- OWASP - Top 10 2017 Category A7 - Cross-Site Scripting (XSS)
- CWE - CWE-1004 - Sensitive Cookie Without 'HttpOnly' Flag
- STIG Viewer - Application Security and Development: V-222575 - The application must set the HTTPOnly flag on session cookies.