Cookies without the Secure attribute

Apply Secure to HTTPS cookies to restrict transmission over HTTP

Description

A cookie (Cookie) without Secure, or with the attribute explicitly disabled, may be sent over HTTP and exposed to an attacker observing network traffic. HTTPS applications should set Secure so cookies are sent over encrypted connections.

Potential impact

Exposure requires the cookie to be sent over HTTP on a path the attacker can observe. The consequences depend on the stored value and session permissions.

  • Session hijacking through intercepted session cookies
  • Disclosure of authentication tokens or personal information
  • Unauthorized account access using a stolen session

Remediation

  1. Use cookie.setSecure(true) in Java, or cookie.secure = true or cookie.setSecure(true) in Kotlin.
  2. Centralize cookie creation and response handling to enforce Secure=true by default.
  3. Operate the service over HTTPS and redirect HTTP requests. A redirect alone cannot protect a cookie already sent in the initial HTTP request.
  4. Apply HttpOnly to sensitive cookies that do not need JavaScript access, and set an appropriate SameSite policy through 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