如何获得通过Web安全性登录的所有用户的列表(通过Spring Security) [英] How can I have list of all users logged in (via spring security) my web application
问题描述
我正在Web应用程序中使用Spring Security,现在我想获得一个已登录程序的所有用户的列表.
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.
我如何访问该列表?他们不是已经在Spring框架中保留了某个位置吗?像 SecurityContextHolder 或 SecurityContextRepository ?
How can I have access to that list? Aren't they already kept somewhere within spring framework? Like SecurityContextHolder or SecurityContextRepository?
推荐答案
要访问所有已登录用户的列表,需要将SessionRegistry实例注入到bean中.
For accessing the list of all logged in users you need to inject SessionRegistry instance to your bean.
@Autowired
@Qualifier("sessionRegistry")
private SessionRegistry sessionRegistry;
然后使用注入的SessionRegistry,您可以访问所有主体的列表:
And then using injcted SessionRegistry you can access the list of all principals:
List<Object> principals = sessionRegistry.getAllPrincipals();
List<String> usersNamesList = new ArrayList<String>();
for (Object principal: principals) {
if (principal instanceof User) {
usersNamesList.add(((User) principal).getUsername());
}
}
但是在注入会话注册表之前,您需要在spring-security.xml中定义会话管理部分(请参见),并发控制部分中,您应该为会话注册表对象设置别名( session-registry-alias >)注入.
But before injecting session registry you need to define session management part in your spring-security.xml (look at Session Management section in Spring Security reference documentation) and in concurrency-control section you should set alias for session registry object (session-registry-alias) by which you will inject it.
<security:http access-denied-page="/error403.jsp" use-expressions="true" auto-config="false">
<security:session-management session-fixation-protection="migrateSession" session-authentication-error-url="/login.jsp?authFailed=true">
<security:concurrency-control max-sessions="1" error-if-maximum-exceeded="true" expired-url="/login.html" session-registry-alias="sessionRegistry"/>
</security:session-management>
...
</security:http>
这篇关于如何获得通过Web安全性登录的所有用户的列表(通过Spring Security)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!