开发者

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

开发者 https://www.devze.com 2023-03-10 19:10 出处:网络
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 b

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("an开发者_运维百科onymous", "anonymous", new ArrayList(Arrays.asList(new GrantedAuthorityImpl("ROLE_ANONYMOUS"))));
    SecurityContextHolder.getContext().setAuthentication(anonymous);
}


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.


The AbstractRememberMeServices class has an implementation of LogoutHandler.logout which cancels the cookie. Inject the LogoutHandler and call this method.

0

精彩评论

暂无评论...
验证码 换一张
取 消