8

I am using Rest response to set cookies on the client side. But I cannot see the cookie being set when I open up 'Resources' in Chrome. But interestingly, when I go to chrome settings and check all cookies, I find the cookies I am setting. Again, getCookie() javascript function from w3schools (or better version to handle all possibilities) fetch me nothing. I tried firefox, there same thing happens. When I see all cookies, I see my cookies, but JS function getCookie() does not return me anything. I think the cookies are not getting set properly.

Here is my JAX-RS response :


    Cookie c1 = new Cookie(Constants.SESSION_TOKEN, response
                .getSessionToken().getValue());

        Cookie c2 = new Cookie(Constants.USER_IDENTIFIER,
                response.getUserIdentifier());

        NewCookie cookie1 = new NewCookie(c1);
        NewCookie cookie2 = new NewCookie(c2);

        return Response.ok(jsonResponse, MediaType.APPLICATION_JSON)
                .cookie(cookie1,cookie2).build();

And this is my JS getCookie() function

    function getCookies() {
        var c = document.cookie, v = 0, cookies = {};
        if (document.cookie.match(/^\s*\$Version=(?:"1"|1);\s*(.*)/)) {
            c = RegExp.$1;
            v = 1;
        }
        if (v === 0) {
            c
                    .split(/[,;]/)
                    .map(
                            function(cookie) {
                                var parts = cookie.split(/=/, 2), name = decodeURIComponent(parts[0]
                                        .trimLeft()), value = parts.length > 1 ? decodeURIComponent(parts[1]
                                        .trimRight())
                                        : null;
                                cookies[name] = value;
                            });
        } else {
            c
                    .match(
                            /(?:^|\s+)([!#$%&'*+\-.0-9A-Z^`a-z|~]+)=([!#$%&'*+\-.0-9A-Z^`a-z|~]*|"(?:[\x20-\x7E\x80\xFF]|\\[\x00-\x7F])*")(?=\s*[,;]|$)/g)
                    .map(
                            function($0, $1) {
                                var name = $0, value = $1.charAt(0) === '"' ? $1
                                        .substr(1, -1).replace(/\\(.)/g, "$1")
                                        : $1;
                                cookies[name] = value;
                            });
        }
        return cookies;
    }
    function getCookie(name) {
        return getCookies()[name];
    }

enter image description here enter image description here

4 Answers4

2

That's strange. I've tried to reproduce your problem, but everything worked fine:

import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;

@GET
@Path(value = "/test")
public Response test() {
    NewCookie c = new NewCookie("name1", "value1");
    Cookie cookie = new Cookie("name2", "value2");
    NewCookie c2 = new NewCookie(cookie);
    return Response.ok("response1").cookie(c, c2).build();
}

curl -i $URL gave me:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Server: Apache-Coyote/1.1
Set-Cookie: name1=value1; Version=1
Set-Cookie: name2=value2; Version=1
Date: Thu, 19 Sep 2013 13:52:43 GMT
Content-Type: application/json
Content-Length: 13

["a","b","c"]

The cookies also showed up in Chrome's Resources.

rzymek
  • 9,064
  • 2
  • 45
  • 59
2

Not sure why your function doesn't get you your cookie information, but I might have an idea why it doesn't show up in your browser.

It helped me to remember that you need to visit the specific path that the cookie was set on for the browser to display the cookie in the console.

In the example above, make sure to visit the url displayed in the "Path:" section.

sainid
  • 82
  • 6
2

For somebody landing on this issue.

This problem occurs when the domain or the path values are not set properly

Use the below snippet to set the path and domain

NewCookie cookie = new NewCookie("cookie-name", "cookie-value,"/", "", "cookie description", 1000000, false);

For example, In your browser you should see these values after its set

Set-Cookie:x-auth-cookie=eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJtbTMiLCJhdWRpZW5jZSI6IkJST1dTRVIiLCJjcmVhdGVkIjoxNDg1MjU4MDcwMzQ2LCJyb2xlcyI6WyJBRE1JTiIsIlRFQUNIRVIiXSwiZXhwIjoxNDg2MjU4MDcwfQ.TM6oiCsOXh2zNou00H-5tkafAj40AngkbrCA62Vdyi5si_5hZFdmZFfitmK_bgRJexmFC49KlpAaRzGJF8bvMQ;Version=1;Comment="cookie description";Domain=;Path=/;Max-Age=1000000
virtuvious
  • 2,362
  • 2
  • 21
  • 22
  • Thank you! I was setting path value to `null` instead of `"/"`, which worked so long as my webserver's path did not include a `/` - for instance `myserver.com/setCookieResource` worked, but `myserver.com/v2/setCookieResource` would not. The only resource I found that explained it well were [these PHP docs](https://www.php.net/manual/en/function.setcookie.php): **If set to '/', the cookie will be available within the entire domain.** – louhow Nov 03 '21 at 03:18
-1

When I set the cookie in the request /home/security/getcookie, with the code below:

NewCookie cookie = new NewCookie("MyCookie", "MyCookieValue", "/", "", 1, null, -1, null, false,false);

It was available as part of request headers only for requests starting with /home/security/ (/home/security/*)

Any other request (home/work/one, /home/employee/getemployee..) the cookie is not available.

Out of curiosity, I did an experiment. Add new API /home/security/testing security rest controller. Cookie was passed to it.

Modified Employee controller, request /home/employee/getemployee to /home/security/employee/getemployee. Cookie did not get passed for this. I was anticipating the cookie was set at "/home/security/" so it would get passed. But no luck

Not able to understand whats happening. Tried all the combinations with NewCookie attributes: domain, path, httpOnly, age... But no luck.

Looks I am encountering this issue Path attribute of Cookie is not affecting for subsequent requests.

But not able to figure out solution. I am running the application on Docker based jetty server.

Asplund
  • 2,254
  • 1
  • 8
  • 19
Pavan Kumar
  • 9
  • 1
  • 2