When a cookie is protected with the secure attribute set to true it will not be send by the browser over an unencrypted HTTP request and thus cannot be observed by an unauthorized person during a man-in-the-middle attack.

Why is this an issue?

When a cookie is created without the secure attribute set to true, browsers will transmit it over unencrypted HTTP connections as well as HTTPS. An attacker who can observe or intercept network traffic—for example on a public Wi-Fi network—can read the cookie value in cleartext.

What is the potential impact?

Session hijacking

If a session cookie is transmitted over an unencrypted HTTP connection, an attacker who can intercept the traffic can steal it. With a valid session cookie, the attacker can impersonate the victim and gain full access to their account without knowing their password. Even on sites that primarily use HTTPS, a single HTTP request containing the session cookie is enough to expose it.

How to fix it in Express.js

Set the secure option to true when creating or configuring cookies.

Code examples

Noncompliant code example

cookie-session module:

let session = cookieSession({
  secure: false // Noncompliant
});

express-session module:

const express = require('express');
const session = require('express-session');

let app = express();
app.use(session({
  cookie:
  {
    secure: false // Noncompliant
  }
}));

cookies module:

let cookies = new Cookies(req, res, { keys: keys });

cookies.set('LastVisit', new Date().toISOString(), {
  secure: false // Noncompliant
});

csurf module:

const cookieParser = require('cookie-parser');
const csrf = require('csurf');
const express = require('express');

let csrfProtection = csrf({ cookie: { secure: false }}); // Noncompliant

Compliant solution

cookie-session module:

let session = cookieSession({
  secure: true
});

express-session module:

const express = require('express');
const session = require('express-session');

let app = express();
app.use(session({
  cookie:
  {
    secure: true
  }
}));

cookies module:

let cookies = new Cookies(req, res, { keys: keys });

cookies.set('LastVisit', new Date().toISOString(), {
  secure: true
});

csurf module:

const cookieParser = require('cookie-parser');
const csrf = require('csurf');
const express = require('express');

let csrfProtection = csrf({ cookie: { secure: true }});

Resources

Standards