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?
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"
);
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);
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();
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