Question

I have the following simple test code at my server http handler:

String cookieString = request.getHeader(COOKIE);

if (cookieString != null) {
    CookieDecoder cookieDecoder = new CookieDecoder();
    Set<Cookie> cookies = cookieDecoder.decode(cookieString);

    if (!cookies.isEmpty()) {
        CookieEncoder cookieEncoder = new CookieEncoder(true);

        for (Cookie cookie : cookies) {
            System.out.println("---> " + cookie);
            cookieEncoder.addCookie(cookie);
        }
        response.addHeader(SET_COOKIE, cookieEncoder.encode());
    }
} else {
    // set cookie for initial time (just testing)
    if (true) {
        CookieEncoder cookieEncoder = new CookieEncoder(true);

        cookieEncoder.addCookie("key", "value");
        cookieEncoder.addCookie("key2", "value2");

        response.addHeader(SET_COOKIE, cookieEncoder.encode());
    } else {
        CookieEncoder cookieEncoder1 = new CookieEncoder(true);
        CookieEncoder cookieEncoder2 = new CookieEncoder(true);

        cookieEncoder1.addCookie("key", "value");
        cookieEncoder2.addCookie("key2", "value2");

        response.addHeader(SET_COOKIE, cookieEncoder1.encode());
        response.addHeader(SET_COOKIE, cookieEncoder2.encode());
    }
}

As you can see, the initial time I try to set two dummy cookies. When I refresh the page (so the cookie is passed through by the client) in FF (does also happen in IE and Chrome), only one cookie is in the header of the request and printed out.

However, if I set the two cookies with a seperate CookieEncoder (see false-clause in code snippet above), everything works as expected.

Is this expected behaviour? I would expect that you can set multiple cookies with one CookieEncoder?

Was it helpful?

Solution 3

I am answering my own question, since it appears to be a issue. See https://github.com/netty/netty/issues/94.

OTHER TIPS

// Initialize Variables
ArrayList<String> cookieArray = new ArrayList<String>();

// Encode 'cooke1' to 'response' Header
encoder.addCookie(cookie1);

// Append 'cookie1' to 'cookieArray'
cookieArray.add(encoder.encode());

// Encode 'cooke2' to 'response' Header
encoder.addCookie(cookie2);

// Append 'cookie2' to 'cookieArray'
cookieArray.add(encoder.encode());

// Create Cookies using 'cookieArray'
response.setHeader("Set-Cookie", cookieArray);

It's actually a violation of HTTP cookie specification to set multiple cookies in a Set-Cookie header. You have to encode only one cookie per Set-Cookie header.

Netty's CookieEncoder allowed doing that and it generated non-compliant Set-Cookie headers.

To fix this issue, the next version of Netty will throw an IllegalStateException if a user attempts to encode more than one cookie on server mode.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top