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.
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.
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.
The following code creates a cookie without enabling the HttpOnly attribute.
let session = cookieSession({
httpOnly: false,// Noncompliant
});
let session = cookieSession({
httpOnly: true,
});
The following code creates a cookie without enabling the HttpOnly attribute.
const express = require('express');
const session = require('express-session');
let app = express();
app.use(session({
cookie:
{
httpOnly: false // Noncompliant
}
}));
const express = require('express');
const session = require('express-session');
let app = express();
app.use(session({
cookie:
{
httpOnly: true
}
}));
The following code creates a cookie without enabling the HttpOnly attribute.
let cookies = new Cookies(req, res, { keys: keys });
cookies.set('LastVisit', new Date().toISOString(), {
httpOnly: false // Noncompliant
});
let cookies = new Cookies(req, res, { keys: keys });
cookies.set('LastVisit', new Date().toISOString(), {
httpOnly: true
});
The following code creates a cookie without enabling the HttpOnly attribute.
const cookieParser = require('cookie-parser');
const csrf = require('csurf');
const express = require('express');
let csrfProtection = csrf({ cookie: { httpOnly: false }}); // Noncompliant
const cookieParser = require('cookie-parser');
const csrf = require('csurf');
const express = require('express');
let csrfProtection = csrf({ cookie: { httpOnly: true }});