春季限制最多会话; 限制最大用户

com*_*tta 5 java spring spring-security

我是否可以使用spring security来限制能够同时登录网站的最大用户数?

肯定的是,不是并发会话控制参数.我想要的是,例如,我想限制最大只允许1000个用户同时登录.如果超过该转发通知页面,则说明超出了最大用户数

Sha*_*eep 8

您可以使用Spring Security的并发会话控制通过访问的SessionRegistry找出当前有多少用户登录.在Spring Security 3中,ConcurrentSessionControlStrategy是负责控制是否允许用户在登录后创建一个会话.您可以扩展这个类,并根据用户数添加额外的检查:

public class MySessionAuthenticationStrategy extends ConcurrentSessionControlStrategy {
    int MAX_USERS = 1000; // Whatever
    SessionRegistry sr;

    public MySessionAuthenticationStrategy(SessionRegistry sr) {
        super(sr);
        this.sr = sr;
    }

    @Override
    public void onAuthentication(Authentication authentication, HttpServletRequest request, HttpServletResponse response) {
        if (sr.getAllPrincipals().size() > MAX_USERS) {
            throw new SessionAuthenticationException("Maximum number of users exceeded");
        }
        super.onAuthentication(authentication, request, response);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以将其注入安全命名空间,如Spring Security参考手册中所述.

在Spring Security 2.0中,并发会话控制的实现略有不同,您可以自定义ConcurrentSessionController.

  • 有关getAllPrincipals的一点是,它也会从过期的会话中返回主体.我发现自己必须使用sr.getAllSessions()遍历所有会话,以检查我是否在计算过期的会话.我的max_users要小得多,过期的会话也没有足够快地清除. (5认同)