How can I have list of all users logged in (via spring security) my web application

后端 未结 7 2316
独厮守ぢ
独厮守ぢ 2020-11-27 12:27

I\'m using spring security in my web application, and now I want to have a list of all users who are logged in my program.

How can I have access to that list? Aren\'

7条回答
  •  清酒与你
    2020-11-27 12:42

    Please correct me if I'm wrong.

    I think @Adam's answer is incomplete. I noticed that sessions already expired in the list were appearing again.

    public class UserController {
        @Autowired
        private SessionRegistry sessionRegistry;
    
        public void listLoggedInUsers() {
            final List allPrincipals = sessionRegistry.getAllPrincipals();
    
            for (final Object principal : allPrincipals) {
                if (principal instanceof SecurityUser) {
                    final SecurityUser user = (SecurityUser) principal;
    
                    List activeUserSessions =
                            sessionRegistry.getAllSessions(principal,
                                    /* includeExpiredSessions */ false); // Should not return null;
    
                    if (!activeUserSessions.isEmpty()) {
                        // Do something with user
                        System.out.println(user);
                    }
                }
            }
        }
    }
    
    
    

    Hope it helps.

    提交回复
    热议问题