Spring Security : Check if user is from remember me cookie
This Spring Security example shows you how to check if a user is login from a “remember me” cookie.
private boolean isRememberMeAuthenticated() {
Authentication authentication =
SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
return false;
}
return RememberMeAuthenticationToken.class.isAssignableFrom(authentication.getClass());
}
@RequestMapping(value = "/admin/update**", method = RequestMethod.GET)
public ModelAndView updatePage() {
ModelAndView model = new ModelAndView();
if (isRememberMeAuthenticated()) {
model.setViewName("/login");
} else {
model.setViewName("update");
}
return model;
}
In Spring Security tag, you can code like this :
<%@taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
<%@page session="true"%>
<html>
<body>
<sec:authorize access="isRememberMe()">
<h2># This user is login by "Remember Me Cookies".</h2>
</sec:authorize>
<sec:authorize access="isFullyAuthenticated()">
<h2># This user is login by username / password.</h2>
</sec:authorize>
</body>
</html>
Note
isRememberMe() – Returns true if the current principal is a remember-me user
isFullyAuthenticated() – Returns true if the user is not an anonymous or a remember-me user
isRememberMe() – Returns true if the current principal is a remember-me user
isFullyAuthenticated() – Returns true if the user is not an anonymous or a remember-me user
isRememberMeAuthenticated() always return false even I checked remember-me. I debugged and see authentication.getClass() always return class org.springframework.security.authentication.UsernamePasswordAuthenticationToken not RememberMeAuthenticationToken. Could you pls help, mkyong?