How do you remove a Cookie in a Java Servlet

JavaServletsCookies

Java Problem Overview


How do you remove a cookie in a Java servlet?

I tried this: http://www.jguru.com/faq/view.jsp?EID=42225

EDIT: The following now works successfully it appears to be the combination of:

response.setContentType("text/html");

and

cookie.setMaxAge(0);

Before I was doing:

//remove single signon cookie if it hasn't been validated yet
response.setContentType("text/html");
Cookie cookie = new Cookie(SSORealm.SSO_COOKIE_NAME, "");
cookie.setDomain(SSORealm.SSO_DOMAIN);
cookie.setMaxAge(-1);
cookie.setPath("/");
cookie.setComment("EXPIRING COOKIE at " + System.currentTimeMillis());
response.addCookie(cookie);

Which expires the cookie when the browser is closed as per the documentation.

> A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.

The full working snippet to expire a cookie is:

//remove single signon cookie if it hasn't been validated yet
response.setContentType("text/html");
Cookie cookie = new Cookie(SSORealm.SSO_COOKIE_NAME, "");
cookie.setDomain(SSORealm.SSO_DOMAIN);
cookie.setMaxAge(0);
cookie.setPath("/");
cookie.setComment("EXPIRING COOKIE at " + System.currentTimeMillis());
response.addCookie(cookie);

Java Solutions


Solution 1 - Java

The MaxAge of -1 signals that you want the cookie to persist for the duration of the session. You want to set MaxAge to 0 instead.

From the API documentation:

A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.

Solution 2 - Java

In my environment, following code works. Although looks redundant at first glance, cookies[i].setValue(""); and cookies[i].setPath("/"); are necessary to clear the cookie properly.

private void eraseCookie(HttpServletRequest req, HttpServletResponse resp) {
	Cookie[] cookies = req.getCookies();
	if (cookies != null)
		for (Cookie cookie : cookies) {
			cookie.setValue("");
			cookie.setPath("/");
			cookie.setMaxAge(0);
			resp.addCookie(cookie);
		}
}

Solution 3 - Java

Keep in mind that a cookie is actually defined by the tuple of it's name, path, and domain. If any one of those three is different, or there is more than one cookie of the same name, but defined with paths/domains that may still be visible for the URL in question, you'll still see that cookie passed on the request. E.g. if the url is "http://foo.bar.com/baz/index.html";, you'll see any cookies defined on bar.com or foo.bar.com, or with a path of "/" or "/baz".

Thus, what you have looks like it should work, as long as there's only one cookie defined in the client, with the name "SSO_COOKIE_NAME", domain "SSO_DOMAIN", and path "/". If there are any cookies with different path or domain, you'll still see the cookie sent to the client.

To debug this, go into Firefox's preferences -> Security tab, and search for all cookies with the SSO_COOKIE_NAME. Click on each to see the domain and path. I'm betting you'll find one in there that's not quite what you're expecting.

Solution 4 - Java

Cookie[] cookies = request.getCookies();
if(cookies!=null)
for (int i = 0; i < cookies.length; i++) {
 cookies[i].setMaxAge(0);
}

did that not worked? This removes all cookies if response is send back.

Solution 5 - Java

This is code that I have effectively used before, passing "/" as the strPath parameter.

public static Cookie eraseCookie(String strCookieName, String strPath) {
	Cookie cookie = new Cookie(strCookieName, "");
	cookie.setMaxAge(0);
	cookie.setPath(strPath);

	return cookie;
}

Solution 6 - Java

The proper way to remove a cookie is to set the max age to 0 and add the cookie back to the HttpServletResponse object.

Most people don't realize or forget to add the cookie back onto the response object. By doing that it will expire and remove the cookie immediately.

...retrieve cookie from HttpServletRequest
cookie.setMaxAge(0);
response.addCookie(cookie);

Solution 7 - Java

One special case: a cookie has no path.

In this case set path as cookie.setPath(request.getRequestURI())

The javascript sets cookie without path so the browser shows it as cookie for the current page only. If I try to send the expired cookie with path == / the browser shows two cookies: one expired with path == / and another one with path == current page.

Solution 8 - Java

When a cookie passed from client to server, it only contains key/value pair, nothing else. which means, when sever receives cookie, it doesn't know

  • if this cookie is http-only
  • if this cookie is secure
  • this cookie's domain
  • this cookie's path

so you may have to manually set domain and path according to the cookie's domain and path in Chrome developer panel.

Let's say you have a cookie:

  • key = dummy-cookie

  • value = dummy-value

  • domain = .bar.com

  • path = / then, if you write sever code like this, it won't work:

          cookie.setValue("");
          cookie.setPath("/");
          cookie.setMaxAge(0);
          resp.addCookie(cookie);
    

because when expoler receives your response, it will match the set-cookie header with local cookies by name, path and domain.

following code works:

        cookie.setValue("");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        cookie.setDomain(".bar.com");
        cookie.setPath("/");
        resp.addCookie(cookie);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDougnukemView Question on Stackoverflow
Solution 1 - JavacjsView Answer on Stackoverflow
Solution 2 - Javawu liangView Answer on Stackoverflow
Solution 3 - JavabroofaView Answer on Stackoverflow
Solution 4 - JavaaholbreichView Answer on Stackoverflow
Solution 5 - JavaKevin HakansonView Answer on Stackoverflow
Solution 6 - JavaAl PalView Answer on Stackoverflow
Solution 7 - JavaUR6LADView Answer on Stackoverflow
Solution 8 - JavaGunslingerView Answer on Stackoverflow