3

Below is my Java code for creating javax.servlet.http.Cookie from Tomcat 7 API

 Cookie c = new Cookie("code", code.trim());
 c.setPath("/public");
 response.addCookie(c);
 response.setStatus(200);

Am trying to add c.setHttpOnly(true); to make the above code sonar compliant but Eclipse is throwing a compiler error saying he method setHttpOnly(boolean) is undefined for the type Cookie, but from the Javadoc of Tomcat 7 API https://tomcat.apache.org/tomcat-7.0-doc/servletapi/index.html I do see that setHttpOnly() exists in Cookie class, can someone please help me Understand why am I getting the compiler error for adding c.setHttpOnly(true);?

OTUser
  • 3,788
  • 19
  • 69
  • 127

2 Answers2

3

The method setHttpOnly of the javax.servlet.http.Cookie class was added in Servlet 3.0 specification.

Tomcat 7 implements Servlet 3.0 spec but in order to compile your code, you need to add appropriate Maven dependencies.

Make sure you have a dependency on Servlet 3.0 API with scope provided:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

With this dependency code cookie.setHttpOnly(true); will compile.

Appending HttpOnly flag to a cookie value manually response.addHeader("Set-Cookie","name=value; HttpOnly"); most likely would not pass SonarQube check.

The rule https://rules.sonarsource.com/java/RSPEC-3330 checks the presence of the setHttpOnly(true) method call.

But this SonarQube check can be suppressed by adding //NOSONAR comment to the end of line causing the warning:

Cookie c = new Cookie("code", code.trim()); //NOSONAR
Eugene Khyst
  • 9,236
  • 7
  • 38
  • 65
1

You probably still use Servlet API 2.5

web.xml specifies the version

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
          version="2.5">

If you use Servlet 2.5, see @dpinya answer for setting HttpOnly:

For Servlet API 2.5, you can use

response.addHeader("Set-Cookie","name=value; HttpOnly");

See also option to set HTTPOnly using context.xml:

The session and SSO cookies in Tomcat 7 are being sent with HttpOnly flag by default, to instruct browsers to prevent access to those cookies from JavaScript. This is considered more secure, but it will prevent JavaScripts from accessing the value of the cookie. This feature can be controlled by useHttpOnly attribute on the Context element. (This feature is also implemented in latest versions of Tomcat 6.0 but is off by default. It can be enabled by setting useHttpOnly="true" on Context element in a web application or in the global CATALINA_BASE/conf/context.xml file).

Ori Marko
  • 56,308
  • 23
  • 131
  • 233