Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring limit max sessions ; limit max users

may i know possible to use spring security to limit max number of users able to login to website at the same time?

definately, not concurrent-session-control parameter. what i want is for instance, i want to limit maximum only allow 1000 users login same time. if more than that forward to notice page stating maximum users exceeded

like image 750
cometta Avatar asked Jan 21 '10 02:01

cometta


2 Answers

You can use Spring Security's concurrent session control by accessing the SessionRegistry to find out how many users are currently logged in. In Spring Security 3, the ConcurrentSessionControlStrategy is responsible for controlling whether the user is allowed to create a session after logging in. You can extend this class and add an extra check based on the number of users:

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);
    }
}

You would then inject this into the security namespace as described in the Spring Security reference manual.

In Spring Security 2.0, the concurrent session control is implemented slightly differently and you would customize the ConcurrentSessionController instead.

like image 176
Shaun the Sheep Avatar answered Sep 25 '22 10:09

Shaun the Sheep


I do not have enough reputation to add a comment. But getAllPrincipals returns all principals including ones from expired sessions. Use some method like below to getAllActiveSessions.

private List<SessionInformation> getActiveSessions(SessionRegistry sessionRegistry) {
    final List<Object> principals = sessionRegistry.getAllPrincipals();
    if (principals != null) {
        List<SessionInformation> sessions = new ArrayList<>();
        for (Object principal : principals) {
            sessions.addAll(sessionRegistry.getAllSessions(principal,     false));
        }
        return sessions;
    }
    return Collections.emptyList();
}
like image 22
Ajinkya Avatar answered Sep 21 '22 10:09

Ajinkya