Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 instanceofs 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?

like image 301
at. Avatar asked Apr 27 '11 21:04

at.


1 Answers

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.

like image 104
Raghuram Avatar answered Sep 26 '22 21:09

Raghuram