How to know if current web visitor logged in with Spring Security 3.0
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?
The proper way to get the currently logged-in user is documented here, which mostly matches the code above.
It looks like you may have anonymous
authentication configured for your site, which is why the principal returns anonymousUser
.
精彩评论