Sensitive cookies without the Secure flag

Sensitive cookies without the Secure flag

Description

Without Secure, a browser may send a cookie containing an authentication token, session ID, or API key in an unencrypted HTTP request.

Potential impact

Even on an HTTPS site, an initial HTTP request can expose the cookie before the redirect to HTTPS. Someone who intercepts a session cookie or token may impersonate the user or access APIs available to that user.

Remediation

  • Set secure: true on sensitive cookies. If you write the Set-Cookie header directly, include Secure to restrict the cookie to HTTPS.
  • Use HttpOnly to limit script access and a SameSite policy suited to the application to reduce CSRF risk.

Examples

Before

javascript
app.post("/login", (req, res) => {
  const token = createSession(req.user);
  res.cookie("session", token, { httpOnly: true });
  res.send("ok");
});

After

javascript
app.post("/login", (req, res) => {
  const token = createSession(req.user);
  res.cookie("session", token, {
    secure: true,
    httpOnly: true,
    sameSite: "Lax",
  });
  res.send("ok");
});

Explanation:

  • Before: The sensitive session cookie lacks Secure and may be sent over HTTP.
  • After: Secure, HttpOnly, and SameSite restrict transmission and access.

References