Search code examples
javaresthttpcookiesdojo

Internet Explorer Cookie from response not overwriting existing Cookies


I have a client server web application, wherein every response from Server will contain a Cookie named fruitCookie.

However, 90 out of 100 times, on the server, the Cookie will be set as:

Cookie cookie = new Cookie("fruitCookie", "someRefreshedValue");
cookie.setPath("/");
httpResponse.addCookie(cookie);

where Cookie is javax.servlet.http.Cookie.

But, the remaining 10 times, on the server, the Cookie will be set from a rest endpoint as:

NewCookie fruitCokie = new NewCookie("fruitCookie", "someRefreshedValue", "/", "", "", -1, false);
return Response.ok().cacheControl(ResourceCache.NO_CACHE).cookie(fruitCookie).build();

where NewCookie is javax.ws.rs.core.NewCookie.

On the client side, I read the cookie using dojo as:

getCookieValue: function (cookieName) {
        return cookie(cookieName); // cookieName is fruitCookie
},

This works fine in Chrome. And the latest Cookie value either from http way or Rest gets read in above function.

However, in IE, its not working. If the rest call sends the Cookie, I can see the new Cookie in response on dev console, however, the call above keeps returning the old value already on the browser and part of the request sent.

I am unsure as is it the IE browser which is causing this or is does it have to do with Path and Domain or is it the way dojo cookie widget works.

How can I solve this issue?


Solution

  • Apparently, IE cares a lot about Domain.

    So changing the following

    NewCookie fruitCokie = new NewCookie("fruitCookie", "someRefreshedValue", "/", "", "", -1, false);
    

    to

    NewCookie fruitCokie = new NewCookie("fruitCookie", "someRefreshedValue", "/", httpRequest.getServerName(), "", -1, false); 
    

    worked as expected.

    Where we can get hold of httpRequest inside Rest as:

    @GET
    @Path("myPath")
    public Response myRestEndPoint(@Context HttpServletRequest httpRequest) {
    

    Note: This will not work on "localhost". Please refer: Set-Cookie header does not set cookie in Internet Explorer