1

I need a public restful endpoint that can tell me if the current user is logged in or not. Since the user may be authenticated as anonymousUser, I can't just do this:

if (SecurityContextHolder.getContext().getAuthentication().isAuthenticated())
...

From looking at some other posts, it looks like I might need to do something clumsy like actually look for the anonymous role in granted authorities. Is there an easier way?

gyoder
  • 4,530
  • 5
  • 29
  • 37

2 Answers2

2

Here's what I believe is the simplest solution:

// permitAll
@RequestMapping(method = RequestMethod.GET, value = "/isAuthorized")
public String isAuthorized(Principal user) {                
    return user != null ? "Y" : "N";
}
gyoder
  • 4,530
  • 5
  • 29
  • 37
0

You can also use (not nice, but works):

SecurityContextHolder.getContext().getAuthentication() != null &&
SecurityContextHolder.getContext().getAuthentication().isAuthenticated() &&
//when Anonymous Authentication
!(SecurityContextHolder.getContext().getAuthentication() 
          instanceof AnonymousAuthenticationToken) 
Dherik
  • 17,757
  • 11
  • 115
  • 164