A cookie's domain specifies which websites should be able to read it. Left blank, browsers are supposed to only send the cookie to sites that exactly match the sending domain. For example, if a cookie was set by lovely.dream.com, it should only be readable by that domain, and not by nightmare.com or even strange.dream.com. If you want to allow sub-domain access for a cookie, you can specify it by adding a dot in front of the cookie's domain, like so: .dream.com. But cookie domains should always use at least two levels.

Cookie domains can be set either programmatically or via configuration. This rule raises an issue when any cookie domain is set with a single level, as in .com.

Ask Yourself Whether

You are at risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Sensitive Code Example

Cookie myCookie = new Cookie("name", "val");
myCookie.setDomain(".com"); // Noncompliant
java.net.HttpCookie myOtherCookie = new java.net.HttpCookie("name", "val");
myOtherCookie.setDomain(".com"); // Noncompliant

Compliant Solution

Cookie myCookie = new Cookie("name", "val"); // Compliant; by default, cookies are only returned to the server that sent them.

// or

Cookie myCookie = new Cookie("name", "val");
myCookie.setDomain(".myDomain.com"); // Compliant

java.net.HttpCookie myOtherCookie = new java.net.HttpCookie("name", "val");
myOtherCookie.setDomain(".myDomain.com"); // Compliant

See