开发者

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜