8

I want to delete cookie on server (by means of setting Expires to the past). How can I do this with javax.ws.rs.core.NewCookie? I'm trying this, but it doesn't work:

return Response.ok()
  .entity("hello world!")
  .cookie(
    new NewCookie(
      "foo",
      "",
      "/",
      ".example.com",
      1,
      "no comment",
      0, // maxAge
      false
    )
  )
  .build();

This snippet produces this HTTP header:

Set-Cookie:foo=;Version=1;Comment="no comment";Domain=.example.com;Path=/

This header doesn't delete the cookie from the server. What is a possible workaround?

yegor256
  • 102,010
  • 123
  • 446
  • 597
  • not a duplicate as this question specifically asks how to do it using JAX-RS `NewCookie` while the other question asks for a general HTTP approach. – Matthijs Wessels Aug 30 '18 at 07:04

4 Answers4

10

This is how it works (rather dirty approach):

return Response.ok()
  .header(
    "Set-Cookie",
    "foo=deleted;Domain=.example.com;Path=/;Expires=Thu, 01-Jan-1970 00:00:01 GMT"
  );
yegor256
  • 102,010
  • 123
  • 446
  • 597
  • Sorry, this response did not removed or changed cookie: Response.ok() .header( "Set-Cookie", "foo=deleted;Expires=Thu, 01-Jan-1970 00:00:01 GMT" ); – RoutesMaps.com Jun 28 '18 at 11:46
  • For cookie: name = "foo" value = "..." comment = null domain = null maxAge = -1 path = null secure = false version = 0 isHttpOnly = false – RoutesMaps.com Jun 28 '18 at 11:48
3

I cannot try proposed, but it should work (since it is common work around for java servlet API to remove cookie).

Step 1. Get access to HttpServletResponse. To do it declare in your service something like:

@Context
HttpServletResponse _currentResponse;

Step 2. Let the client side chance to remove cookie by set expiration time

Cookie userCookie = new Cookie(cookieName, "");
_currentResponse.setContentType("text/html");
userCookie.setMaxAge(0);
_currentResponse.addCookie(userCookie);
Dewfy
  • 23,277
  • 13
  • 73
  • 121
1

This worked for me! Note that I'm setting the max age to 0 and the expiration date to the current time.

NewCookie mycookie= new NewCookie("mycookie", null, "/", "", NewCookie.DEFAULT_VERSION, null, 0, new Date(), false, false);
return Response.ok().cookie(mycookie).build();
Amber
  • 2,413
  • 1
  • 15
  • 20
0

this works as well:

NewCookie mycookie = new NewCookie("mycookie", null, "/", null, null, 0, false, true);
return Response.ok().cookie(mycookie).build();

extract from response header:

set-cookie: mycookie=;Version=1;Path=/;Max-Age=0;HttpOnly
aegyed
  • 1,320
  • 3
  • 20
  • 39