Unspecified JavaScript cookie accessibility
Why is this an issue?
This rule identifies a Security vulnerability where cookies are created without the isHttpOnly flag specified.
The isHttpOnly parameter controls whether a cookie is accessible by JavaScript. When not set to true, cookies become vulnerable to cross-site scripting (XSS) attacks where malicious scripts can steal session tokens or other sensitive data stored in cookies.
Examples
Example of incorrect code: The following code creates a cookie using the 6-parameter constructor, which does not specify isHttpOnly.
Cookie sessionCookie = new Cookie(
'sessionId',
sessionValue,
'/',
3600,
true, // isSecure
'Strict' // SameSite
);
Example of correct code: The following code creates a secure cookie by using the 7-parameter constructor with isHttpOnly set to true. This prevents JavaScript from accessing the cookie, mitigating XSS attacks.
Cookie secureCookie = new Cookie(
'sessionId',
sessionValue,
'/',
3600,
true, // isSecure
'Strict', // SameSite
true // isHttpOnly
);
Example of correct code: The following code creates an insecure cookie by using the 7-parameter constructor with isHttpOnly set to false. This makes it explicit that this cookie is not secure against XSS attacks.
Cookie insecureCookie = new Cookie(
'sessionId',
sessionValue,
'/',
3600,
true, // isSecure
'Strict', // SameSite
false // isHttpOnly
);
How can I fix violations?
Use the 7-parameter Cookie constructor and specify isHttpOnly.
When should I disable this rule?
It's always a good idea to specify the flag to make it clear that there has been an intentional decision. It can be set to false for cookies that intentionally need JavaScript access for legitimate client-side functionality, provided they contain no sensitive data.
Resources
