Reputation: 161
i want get online users list
this is my code
web.xml
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
spring-security.xml
<security:http auto-config="true">
<security:session-management>
<security:concurrency-control max-sessions="1" expired-url="/login?expire" />
</security:session-management>
</security:http>
and service
@Service
public class UserSessionRegistry {
@Autowired
private SessionRegistry sessionRegistry;
public List<User> getOnlineUsers() {
List<User> retValue = new ArrayList<User>();
List<Object> onlineUsers = sessionRegistry.getAllPrincipals();
for (Object usr : onlineUsers) {
retValue.add((User) usr);
}
return retValue;
}
}
but always return null as results
Upvotes: 0
Views: 2821
Reputation: 370
By using this code you can get all online user except the user which try to get.
And Implement SessionRegistry bean first into your spring-security configuraton.
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String userName = auth.getName();
List<Object> principals = sessionRegistry.getAllPrincipals();
List<UserInfo> usersInfoList = new ArrayList<UserInfo>();
for (Object principal: principals) {
if (principal instanceof UserInfo) {
if(!((UserInfo) principal).getUsername().equals(userName)){
for(SessionInformation sess :sessionRegistry.getAllSessions(principal, false)){
if(!sess.isExpired()){
usersInfoList.add((UserInfo) sess.getPrincipal());
}
}
}
}
Upvotes: 1
Reputation: 161
spring-security have changed as below and the result was correct
<bean id="sessionRegistry"
class="org.springframework.security.core.session.SessionRegistryImpl" />
<security:http auto-config="true">
<security:session-management>
<security:concurrency-control
session-registry-ref="sessionRegistry" max-sessions="1" expired-url="/login?expire" />
</security:session-management>
</security:http>
Upvotes: 0
Reputation: 13262
According to spring docs you need to setup the concurrency-control and use maximumSession
set to -1
(if you don't need to control the number of concurrent sessions). This way you will register the SessionRegistry
and have access to the principal information.
Upvotes: 0