Sensei Logo Sensei Hub

Recipe - Session configuration: Cookies: Set Secure flag to true

Description:
Prevent a cookie being sent over unencrypted HTTP by setting the Secure flag to true
Level:
error
Language:
  • java
Tags:
  • Spring
  • security
  • framework specific
  • web
  • Spring Boot
  • OWASP Top 10
Documentation

Cookies should be configured securely using the http-only and secure settings.

Using setSecure(true) ensures the cookie is only sent over HTTPS. Otherwise, when using the default setting, the cookie will be sent over an unencrypted HTTP connection. This enables attackers to sniff the contents of the cookie, possibly leading to disclosure of the session ID's via a Man-in-the-Middle attack.

Using setHttpOnly(true), can only be accessed through the HTTP protocol, protecting it from client-side scripts. Cookies are frequently the target of Cross-Site Scripting (XSS) attacks. Setting these flags will mitigate many XSS attack vectors.

Before
Cookie cookie = new Cookie("name", "value");
After
Cookie cookie = new Cookie("name", "value");
cookie.setSecure(true);
cookie.setHttpOnly(true);
Resources
Recipe
id: scw:spring:cookie:set-secure
version: 10
metadata:
  name: 'Session configuration: Cookies: Set Secure flag to true'
  shortDescription: Prevent a cookie being sent over unencrypted HTTP by setting the Secure flag to true
  level: error
  language: java
  scwCategory: improper_session_handling:improper_flags_in_cookie_headers
  enabled: true
  descriptionFile: descriptions/CookieFlags.html
  tags: Spring;security;framework specific;web;Spring Boot;OWASP Top 10
search:
  methodcall:
    args:
      1:
        type: boolean
        value:
          stringified: "false"
    name:
      matches: setSecure
    declaration:
      type: org.springframework.boot.web.servlet.server.Session.Cookie
availableFixes:
- name: Set Secure to true
  actions:
  - modifyArguments:
      rewrite:
        1: "true"