gyoder
gyoder

Reputation: 4738

Spring security: is the user logged in or anonymous?

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?

Upvotes: 1

Views: 4952

Answers (2)

Dherik
Dherik

Reputation: 19110

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

SecurityContextHolder.getContext().getAuthentication() != null &&
SecurityContextHolder.getContext().getAuthentication().isAuthenticated() &&
//when Anonymous Authentication
!(SecurityContextHolder.getContext().getAuthentication() 
          instanceof AnonymousAuthenticationToken) 

Upvotes: 0

gyoder
gyoder

Reputation: 4738

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";
}

Upvotes: 2

Related Questions