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: trueon sensitive cookies. If you write theSet-Cookieheader directly, includeSecureto restrict the cookie to HTTPS. - Use
HttpOnlyto limit script access and aSameSitepolicy 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
Secureand may be sent over HTTP. - After:
Secure,HttpOnly, andSameSiterestrict transmission and access.