Dougnukem
Dougnukem

Reputation: 14927

How do you remove a Cookie in a Java Servlet

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);

Upvotes: 149

Views: 260128

Answers (8)

Gunslinger
Gunslinger

Reputation: 1

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);

Upvotes: 0

Al Pal
Al Pal

Reputation: 335

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);

Upvotes: 4

Radio Rogal
Radio Rogal

Reputation: 457

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.

Upvotes: 0

wu liang
wu liang

Reputation: 2013

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);
        }
}

Upvotes: 76

cjs
cjs

Reputation: 27291

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.

Upvotes: 152

aholbreich
aholbreich

Reputation: 5089

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.

Upvotes: 9

Kevin Hakanson
Kevin Hakanson

Reputation: 42240

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;
}

Upvotes: 8

broofa
broofa

Reputation: 38151

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.

Upvotes: 14

Related Questions