我如何获得登录(通过 spring 安全性)我的 Web 应用程序的所有用户的列表 [英] How can I have list of all users logged in (via spring security) my web application

查看:32
本文介绍了我如何获得登录(通过 spring 安全性)我的 Web 应用程序的所有用户的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 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 框架中的某个地方了吗?像 SecurityContextHolderSecurityContextRepository 吗?

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 中定义会话管理部分(查看 Spring Security 参考文档中的会话管理部分)和并发控制部分,您应该为会话注册表对象设置别名(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>

这篇关于我如何获得登录(通过 spring 安全性)我的 Web 应用程序的所有用户的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆