Main Tutorials

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

References

  1. Spring Security, Spring EL for expression overview
  2. AuthenticationTrustResolverImpl JavaDoc
  3. Spring Security Remember Me example

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Hung V. PHAM
6 years ago

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?