Search code examples
javatomcatjersey

Set httpOnly in NewCookie using Jersey


I want to set httpOnly on a NewCookie created by Jersey.

I am using the following library for Jersey:

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-core</artifactId>
            <version>1.19.4</version>
        </dependency>

This uses javax.ws.rs:jsr311-api:1.1.1 which doesn't seem to support httpOnly in NewCookie.

Which Jersey library should I use with Tomcat if I want to have a httpOnly cookie?


Solution

  • You need to use JAX-RS/Jersey 2.x For that, use the following dependency

    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId>
        <version>2.32</version>
    </dependency>
    

    If you need support for JSON/POJO mapping, add the following

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>2.32</version>
    </dependency>
    

    You should also remove any dependencies you currently are using that are for Jersey 1.x. Leaving them may cause some conflict and cause your app to not work. If you find out you need any other features for Jersey that require other jars, make sure you use the same version.

    Note: If for any reason, you must stick with using Jersey 1.x, a cookie is sent simply by sending a Set-Cookie response header. When the browser sends it back to the server, is in the form of a Cookie request header. So you could use cookies without needing the actual NewCookie and Cookie classes that JAX-RS 2.x offers by simple working with headers. See Using HTTP cookies.