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

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

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

您可以通过访问SessionRegistry来查看当前登录的用户数量来使用Spring Security的并发会话控制。在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); } } 

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

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

我没有足够的声誉来添加评论。 但getAllPrincipals返回所有主体,包括来自过期会话的主体。 使用下面的方法来getAllActiveSessions。

 private List getActiveSessions(SessionRegistry sessionRegistry) { final List principals = sessionRegistry.getAllPrincipals(); if (principals != null) { List sessions = new ArrayList<>(); for (Object principal : principals) { sessions.addAll(sessionRegistry.getAllSessions(principal, false)); } return sessions; } return Collections.emptyList(); } 

这篇文章有点旧,但我在spring security 4.1中遇到了同样的问题,我已经解决了这个问题。

会话管理

     

会话的认证策略-REF

                 

的SessionRegistry

 @Autowired private SessionRegistry sessionRegistry; 

认证

 List sessions = new ArrayList<>(); for (Object principal : sessionRegistry.getAllPrincipals()) { sessions.addAll(sessionRegistry.getAllSessions(principal, false)); } LOGGER.info("Sessiones Activas: " + sessions.size()); // filtro para limite de sessiones if (sessions.size() < max_sessions) { //authentication } else { throw new SessionAuthenticationException("Maximo numero de Usuarios exedido."); } 

这样,因为我基于安全性进行身份validation:自定义filter