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

Cookie cookie = new Cookie(COOKIENAME, sensitivedata);
cookie.setHttpOnly(false);  // Noncompliant

Compliant solution

Cookie cookie = new Cookie(COOKIENAME, sensitivedata);
cookie.setHttpOnly(true);

Resources

Documentation

Standards