spring-lemon
spring-lemon copied to clipboard
Restrict Spring Security maximum sessions, and force logout when roles change
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 https://github.com/spring-projects/spring-boot/issues/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.