0

I want to retrieve the currently logged in users by leveraging spring's SessionRegistry.

I have defined the bean and applied it to the session management as shown below:

@Override
protected void configure(final HttpSecurity http) throws Exception {
    http.sessionManagement().maximumSessions(1).sessionRegistry(sessionRegistry());
}

@Bean
public SessionRegistry sessionRegistry() {
   return new SessionRegistryImpl();
}

Then I've created the method to get all users:

@Autowired
private SessionRegistry sessionRegistry;

@Override
public List<String> getUsersFromSessionRegistry() {
 return sessionRegistry.getAllPrincipals().stream()
   .filter(u -> !sessionRegistry.getAllSessions(u, false).isEmpty())
   .map(Object::toString)
   .collect(Collectors.toList());
}

I added a method in the controller but it returns always an empty list

@GetMapping("/loggedUsersFromSessionRegistry")
public List<String> getLoggedUsersFromSessionRegistry() {
    return userService.getUsersFromSessionRegistry();
}
Aleksandar G
  • 1,163
  • 2
  • 20
  • 25
akanzari
  • 77
  • 1
  • 1
  • 7

1 Answers1

0
public List<String> getUsersFromSessionRegistry() {
    return sessionRegistry.getAllPrincipals()
        .stream()
        .filter((u) -> !sessionRegistry.getAllSessions(u, false)
            .isEmpty())
        .map(o -> {
            if (o instanceof User) {
                return ((User) o).getEmail();
            } else {
                return o.toString();
            }
        })
        .collect(Collectors.toList());

}
rnedit
  • 11
  • 1