Reputation: 52590
We're using Spring Framework and Spring Security 3.0.x, how do we know if the current visitor is logged in and what their username is? I've always had the following code:
public static String getUsername() {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal == null)
return null;
if (principal instanceof String)
return (String) principal;
if (principal instanceof User)
return ((User) principal).getUsername();
return null;
}
The reason for the instanceof
s is in the past sometimes getPrincipal()
would return a String
and sometimes a User
...
So I would simply check if getUsername()
returned null
to see if the current visitor was logged in. However, something changed in our Spring libraries when upgrading some components recently. Now if the user is not logged in, getPrincipal()
returns the String
"anonymousUser".
Going forward, what's the proper way I'm supposed to be checking if a visitor is logged in and what their username is?
Upvotes: 6
Views: 8088