Description
If Secure is missing or disabled, the browser may send a cookie over HTTP even when an HTTPS service issued it.
Potential impact
Anyone who can observe that HTTP traffic may read the cookie. Depending on what it contains, this can expose an authentication token or personal data, or let someone use a session with the user’s permissions.
Remediation
- Make
Secure=truethe default in the shared code that creates cookies and adds them to responses. Usecookie.setSecure(true)in Java, orcookie.secure = trueorcookie.setSecure(true)in Kotlin. - Serve the entire application over HTTPS and redirect HTTP requests to HTTPS. A cookie included in the first HTTP request is already exposed by the time the redirect occurs.
- Set
HttpOnlyon sensitive cookies that JavaScript does not need to read. Choose aSameSitepolicy for the service using a supported API or theSet-Cookieheader.
Examples
These ordinary preference cookies demonstrate only the transport attribute. Assess sensitivity from the values and their use, not the names alone.
Java
Before
java
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
void addPreferenceCookie(HttpServletResponse response, String value) {
Cookie cookie = new Cookie("theme", value);
cookie.setSecure(false);
response.addCookie(cookie);
}
After
java
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
void addPreferenceCookie(HttpServletResponse response, String value) {
Cookie cookie = new Cookie("theme", value);
cookie.setSecure(true);
response.addCookie(cookie);
}
Kotlin
Before
kotlin
import jakarta.servlet.http.Cookie
import jakarta.servlet.http.HttpServletResponse
fun addPreferenceCookie(response: HttpServletResponse, value: String) {
val cookie = Cookie("preferences", value)
cookie.secure = false
response.addCookie(cookie)
}
After
kotlin
import jakarta.servlet.http.Cookie
import jakarta.servlet.http.HttpServletResponse
fun addPreferenceCookie(response: HttpServletResponse, value: String) {
val cookie = Cookie("preferences", value)
cookie.secure = true
response.addCookie(cookie)
}