Cookies without the Secure attribute

Apply Secure to HTTPS cookies to restrict transmission over HTTP

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

  1. Make Secure=true the default in the shared code that creates cookies and adds them to responses. Use cookie.setSecure(true) in Java, or cookie.secure = true or cookie.setSecure(true) in Kotlin.
  2. 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.
  3. Set HttpOnly on sensitive cookies that JavaScript does not need to read. Choose a SameSite policy for the service using a supported API or the Set-Cookie header.

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)
}

References