The HttpOnly cookie attribute tells the browser to prevent client-side scripts from reading cookies with the attribute, and its use can go a long way to defending against Cross-Site Scripting (XSS) attacks. Thus, as a precaution, the attribute should be set by default on all cookies set server-side, such as session id cookies.

When implementing Cross Site Request Forgery (XSRF) protection, a JavaScript-readable session cookie, generally named XSRF-TOKEN, should be created on the first HTTP GET request. For such a cookie, the HttpOnly attribute should be set to "false".

Setting the attribute can be done either programmatically, or globally via configuration files.

Noncompliant Code Example

Cookie cookie = new Cookie("myCookieName", value); // Noncompliant; by default cookie.isHttpOnly() is returning false

Compliant Solution

Cookie cookie = new Cookie("myCookieName", value);
cookie.setHttpOnly(true); // Compliant

See