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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With