This rule safeguards sensitive user data stored in cookies from unauthorized access. When a cookie is marked as secure, it informs the browser that the cookie should only be sent over an encrypted HTTPS connection. If this flag is not set, the cookie can be transmitted over insecure connections, exposing the data to potential eavesdropping by attackers.
This rule is vital to maintain the confidentiality and integrity of user data, particularly in cases where cookies store sensitive information like session identifiers or authentication tokens. Non-compliance with this rule can lead to serious security vulnerabilities, including session hijacking and data theft.
To adhere to this rule, always set the secure flag to true when creating a cookie. It is also recommended to set the httpOnly flag to true to prevent the cookie from being accessed by client-side scripts, providing an additional layer of protection against cross-site scripting (XSS) attacks. For example, val cookie = Cookie(name, value).apply { httpOnly = true; secure = true }. This way, you ensure that your cookies are sent only over secure connections and are not accessible via client-side scripting.
Non-Compliant Code Examples
importjavax.servlet.http.Cookieimportjavax.servlet.http.HttpServletResponseclassCookieManager{funcreateCookie(response:HttpServletResponse){// Dangerous: Cookie without HttpOnly flag
valcookie=Cookie("sessionId",generateSessionId())response.addCookie(cookie)}funcreateCookie2(response:HttpServletResponse){// Dangerous: Explicitly disabled HttpOnly
valinsecureCookie=Cookie("userData",userJson)insecureCookie.setHttpOnly(false)response.addCookie(insecureCookie)}funcreateSecureCookieButNotHttpOnly(response:HttpServletResponse){valcookie=Cookie("authToken",token)cookie.secure=true// SSL/TLS only, but missing HttpOnly
response.addCookie(cookie)}}