Skip to content

Restrict Spring Security maximum sessions, and force logout when roles change #2

@naturalprogrammer

Description

@naturalprogrammer

Allow application developers to restrict the number of maximum login sessions for a user by using a property such as lemon.security.max-sessions: 5. A default, say 5, can be set.

Coding this feature will also allow us to go a step further and force logout a user when an admin alters his roles.

References:

http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#concurrent-sessions
spring-projects/spring-boot#1537
https://jira.spring.io/browse/SEC-3069

I think we need to add some code to LemonSecurityConfig, like this:

@Override
protected void configure(HttpSecurity http) throws Exception {

     http
          ...
      .sessionManagement()
        .maximumSessions(10)
        .sessionRegistry(sessionRegistry());
     ...
}

/**
 * Until https://jira.spring.io/browse/SEC-2855
 * is closed, we need to have this custom sessionRegistry
 */
@Bean
public SessionRegistry sessionRegistry() {
    SessionRegistry sessionRegistry = new SessionRegistryImpl();
    return sessionRegistry;
}

/**
 * Register HttpSessionEventPublisher. Note that it is declared
 * static to instantiate it very early, before this configuration
 * class is processed.
 * 
 * See http://docs.spring.io/spring-boot/docs/current/reference/html/howto-embedded-servlet-containers.html
 * for how to add a ServletContextListener.
 * 
 * See http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Bean.html
 * for how static instantiation works.
 */
@Bean
public static ServletListenerRegistrationBean<HttpSessionEventPublisher> httpSessionEventPublisher() {
    return new ServletListenerRegistrationBean<HttpSessionEventPublisher>(new HttpSessionEventPublisher());
}

But, for scaling up, won't we need to have our own SessionRegistry implementation, say JPA based, instead of SessionRegistryImpl, which is the in-memory based? I also noticed that SessionRegistryImpl only listens to SessionDestroyedEvent. Should not it be listening to SessionCreatedEvent as well? Need to study more.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions