Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security: How to clear `remember me` cookie programmatically?

I'm using logout method in web-app like below, but if i check remember me logout doesn't work, because cookie isn't cleared. How to clear programmatically this cookie in my method (or how to make better logout method) ?

public void logout() {
    AnonymousAuthenticationToken anonymous = new AnonymousAuthenticationToken("anonymous", "anonymous", new ArrayList(Arrays.asList(new GrantedAuthorityImpl("ROLE_ANONYMOUS"))));
    SecurityContextHolder.getContext().setAuthentication(anonymous);
}
like image 724
marioosh Avatar asked Jun 07 '11 12:06

marioosh


1 Answers

If you are using the standard Spring Security cookie name (which is SPRING_SECURITY_REMEMBER_ME_COOKIE), you can do this:

void cancelCookie(HttpServletRequest request, HttpServletResponse response)
{
  String cookieName = "SPRING_SECURITY_REMEMBER_ME_COOKIE";
  Cookie cookie = new Cookie(cookieName, null);
  cookie.setMaxAge(0);
  cookie.setPath(StringUtils.hasLength(request.getContextPath()) ? request.getContextPath() : "/");
  response.addCookie(cookie);
}

You'll have to change the cookieName value if you are using a custom cookie name.

like image 107
Femi Avatar answered Nov 12 '22 05:11

Femi