Buddhika Ariyaratne
Buddhika Ariyaratne

Reputation: 2423

Make all cookies secure in a JSF Application

How can I make all cookies secure in a Java Web / JSF Application?

I added the following lines to web.xml to make JSESSIONID secure and httpOnly. Yet, the other cookies are not secure.

<session-config>
    <session-timeout>
        15
    </session-timeout>
    <cookie-config>
        <http-only>true</http-only>
        <secure>true</secure>
        <max-age>6000</max-age>
    </cookie-config>
</session-config>

If that can be achieved by changing the web.xml file, that will be great.

Upvotes: 1

Views: 1145

Answers (2)

Jonathan S. Fisher
Jonathan S. Fisher

Reputation: 8817

I don't believe this selected answer above is correct for what you're asking. It's true that you can create a secure cookie using that method, but you're asking about the session cookie, which is not created using the method he describes.

The configuration you have is correct though, but only works if your container supports it.

  • You must be on a recent lineage of tomcat (7.x, 8.x, 9.x, etc)
  • You must use the latest version in the lineage (9.0.64 at the time of this writing)
  • Your web.xml must declare/use a supported schema. You only posted a snippet of your web.xml. I checked the web-common_3_0.xsd and it has the http-only and secure elements in it. As such, you must use web.xml schema of 3.0 or greater:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0">

I tested this locally on the most recent version of Tomcat 9 and the cookie was produced correctly.

Upvotes: 1

Forketyfork
Forketyfork

Reputation: 7810

A cookie can be arbitrarily created and attached to the response by your code or by the code of the frameworks that you use. The default value of the secure flag is false, according to the servlet API. You can use Cookie.setSecure() method to set this flag to true for any particular cookie, but there's no way to enforce this flag to always be true. You'd have to solve this issue for every particular case.

Upvotes: 1

Related Questions