Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a cookie on server with JAX-RS NewCookie?

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?

like image 341
yegor256 Avatar asked Nov 10 '11 13:11

yegor256


3 Answers

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"
  );
like image 176
yegor256 Avatar answered Oct 06 '22 08:10

yegor256


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);
like image 41
Dewfy Avatar answered Oct 06 '22 07:10

Dewfy


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();
like image 1
Amber Avatar answered Oct 06 '22 07:10

Amber