Spring security session registry (#473)

*  Spring Security Concurrent Session Integration #65

 add SpringSessionBackedSessionRegistry

*  Spring Security Concurrent Session Integration #65

 add documentation

*  Spring Security Concurrent Session Integration #65

support marking SessionInformations as expired before deleting the Session
This commit is contained in:
Joris Kuipers
2016-09-02 21:01:41 +02:00
committed by Rob Winch
parent 8db7d394ba
commit 2724b333b3
8 changed files with 469 additions and 2 deletions

View File

@@ -30,6 +30,7 @@ dependencies {
"org.springframework:spring-websocket:${springVersion}",
"org.springframework:spring-messaging:${springVersion}",
"org.springframework:spring-jdbc:${springVersion}",
"org.springframework.security:spring-security-config:${springSecurityVersion}",
"org.springframework.security:spring-security-web:${springSecurityVersion}",
"org.springframework.security:spring-security-test:${springSecurityVersion}",
'junit:junit:4.11',

View File

@@ -505,6 +505,43 @@ Before using WebSocket integration, you should be sure that you have <<httpsessi
include::guides/websocket.adoc[tags=config,leveloffset=+2]
[[spring-security-concurrent-sessions]]
== Spring Security Integration
Spring Session provides integration with Spring Security to support its concurrent session control.
This allows limiting the number of active sessions that a single user can have concurrently, but unlike the default
Spring Security support this will also work in a clustered environment. This is done by providing a custom
implementation of Spring Security's `SessionRegistry` interface.
[[spring-security-concurrent-sessions-how]]
=== Configuring Spring Security's concurrent session management
When using Spring Security's Java config DSL, you can configure the custom `SessionRegistry` through the
`SessionManagementConfigurer` like this:
[source,java,indent=0]
----
include::{docs-test-dir}docs/security/SecurityConfiguration.java[tags=class]
----
This assumes that you've also configured Spring Session to provide a `FindByIndexNameSessionRepository` that
returns `ExpiringSession` instances.
When using XML configuration, it would look something like this:
[source,xml,indent=0]
----
include::{docs-test-resources-dir}docs/security/security-config.xml[tags=config]
----
This assumes that your Spring Session `SessionRegistry` bean is called `sessionRegistry`, which is the name used by all
`SpringHttpSessionConfiguration` subclasses except for the one for MongoDB: there it's called `mongoSessionRepository`.
[[spring-security-concurrent-sessions-limitations]]
=== Limitations
Spring Session's implementation of Spring Security's `SessionRegistry` interface does not support the `getAllPrincipals`
method, as this information cannot be retrieved using Spring Session. This method is never called by Spring Security,
so this only affects applications that access the `SessionRegistry` themselves.
[[api]]
== API Documentation
@@ -837,7 +874,7 @@ For example, Java Configuration can use the following:
include::{docs-test-dir}docs/RedisHttpSessionConfigurationNoOpConfigureRedisActionTests.java[tags=configure-redis-action]
----
XML Configuraiton can use the following:
XML Configuration can use the following:
[source,xml,indent=0]
----

View File

@@ -0,0 +1,52 @@
/*
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package docs.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.session.ExpiringSession;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.security.SpringSessionBackedSessionRegistry;
/**
* @author Joris Kuipers
*/
// tag::class[]
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
FindByIndexNameSessionRepository<ExpiringSession> sessionRepository;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// other config goes here...
.sessionManagement()
.maximumSessions(2)
.sessionRegistry(sessionRegistry());
}
@Bean
SpringSessionBackedSessionRegistry sessionRegistry() {
return new SpringSessionBackedSessionRegistry(this.sessionRepository);
}
}
// end::class[]

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<!-- tag::config[] -->
<security:http>
<!-- other config goes here... -->
<security:session-management>
<security:concurrency-control max-sessions="2" session-registry-ref="sessionRegistry"
</security:session-management>
</security:http>
<bean id="sessionRegistry"
class="org.springframework.session.security.SpringSessionBackedSessionRegistry">
<constructor-arg ref="sessionRepository"/>
</bean>
<!-- end::config[] -->
</beans>

View File

@@ -24,7 +24,8 @@ dependencies {
"org.springframework:spring-context:$springVersion",
"org.springframework:spring-web:$springVersion",
"org.springframework:spring-messaging:$springVersion",
"org.springframework:spring-websocket:$springVersion"
"org.springframework:spring-websocket:$springVersion",
"org.springframework.security:spring-security-core:$springSecurityVersion"
provided "javax.servlet:javax.servlet-api:$servletApiVersion"
integrationTestCompile "redis.clients:jedis:$jedisVersion",
"org.apache.commons:commons-pool2:2.2",

View File

@@ -0,0 +1,92 @@
/*
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session.security;
import java.util.Date;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.session.ExpiringSession;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;
import org.springframework.session.SessionRepository;
/**
* Ensures that calling {@link #expireNow()} propagates to Spring Session,
* since this session information contains only derived data and is not the authoritative source.
*
* @author Joris Kuipers
* @since 1.3
*/
class SpringSessionBackedSessionInformation extends SessionInformation {
static final String EXPIRED_ATTR = SpringSessionBackedSessionInformation.class.getName() + ".EXPIRED";
private static final Log logger = LogFactory.getLog(SpringSessionBackedSessionInformation.class);
private static final String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT";
/**
* Tries to determine the principal's name from the given Session.
*
* @param session Spring Session session
* @return the principal's name, or empty String if it couldn't be determined
*/
private static String resolvePrincipal(Session session) {
String principalName = session.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME);
if (principalName != null) {
return principalName;
}
SecurityContext securityContext = session.getAttribute(SPRING_SECURITY_CONTEXT);
if (securityContext != null && securityContext.getAuthentication() != null) {
return securityContext.getAuthentication().getName();
}
return "";
}
private final SessionRepository<ExpiringSession> sessionRepository;
SpringSessionBackedSessionInformation(ExpiringSession session, SessionRepository<ExpiringSession> sessionRepository) {
super(resolvePrincipal(session), session.getId(), new Date(session.getLastAccessedTime()));
this.sessionRepository = sessionRepository;
if (Boolean.TRUE.equals(session.getAttribute(EXPIRED_ATTR))) {
super.expireNow();
}
}
@Override
public void expireNow() {
if (logger.isDebugEnabled()) {
logger.debug("Expiring session " + getSessionId() + " for user '" + getPrincipal() +
"', presumably because maximum allowed concurrent sessions was exceeded");
}
super.expireNow();
ExpiringSession session = this.sessionRepository.getSession(getSessionId());
if (session != null) {
session.setAttribute(EXPIRED_ATTR, Boolean.TRUE);
this.sessionRepository.save(session);
}
else {
logger.info("Could not find Session with id " + getSessionId() + " to mark as expired");
}
}
}

View File

@@ -0,0 +1,113 @@
/*
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session.security;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.session.ExpiringSession;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.util.Assert;
/**
* A {@link SessionRegistry} that retrieves session information from Spring Session, rather than maintaining it itself.
* This allows concurrent session management with Spring Security in a clustered environment.
* <p>
* Relies on being able to derive the same String-based representation of the principal given to
* {@link #getAllSessions(Object, boolean)} as used by Spring Session in order to look up the user's sessions.
* <p>
* Does not support {@link #getAllPrincipals()}, since that information is not available.
*
* @author Joris Kuipers
* @since 1.3
*/
public class SpringSessionBackedSessionRegistry implements SessionRegistry {
private final FindByIndexNameSessionRepository<ExpiringSession> sessionRepository;
public SpringSessionBackedSessionRegistry(FindByIndexNameSessionRepository<ExpiringSession> sessionRepository) {
Assert.notNull(sessionRepository, "sessionRepository cannot be null");
this.sessionRepository = sessionRepository;
}
public List<Object> getAllPrincipals() {
throw new UnsupportedOperationException("SpringSessionBackedSessionRegistry does not support retrieving all principals, " +
"since Spring Session provides no way to obtain that information");
}
public List<SessionInformation> getAllSessions(Object principal, boolean includeExpiredSessions) {
Collection<ExpiringSession> sessions =
this.sessionRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, name(principal)).values();
List<SessionInformation> infos = new ArrayList<SessionInformation>();
for (ExpiringSession session : sessions) {
if (includeExpiredSessions || !Boolean.TRUE.equals(session.getAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR))) {
infos.add(new SpringSessionBackedSessionInformation(session, this.sessionRepository));
}
}
return infos;
}
public SessionInformation getSessionInformation(String sessionId) {
ExpiringSession session = this.sessionRepository.getSession(sessionId);
if (session != null) {
return new SpringSessionBackedSessionInformation(session, this.sessionRepository);
}
return null;
}
/*
* This is a no-op, as we don't administer sessions ourselves.
*/
public void refreshLastRequest(String sessionId) {
}
/*
* This is a no-op, as we don't administer sessions ourselves.
*/
public void registerNewSession(String sessionId, Object principal) {
}
/*
* This is a no-op, as we don't administer sessions ourselves.
*/
public void removeSessionInformation(String sessionId) {
}
/**
* Derives a String name for the given principal.
*
* @param principal as provided by Spring Security
* @return name of the principal, or its {@code toString()} representation if no name could be derived
*/
protected String name(Object principal) {
if (principal instanceof UserDetails) {
return ((UserDetails) principal).getUsername();
}
if (principal instanceof Principal) {
return ((Principal) principal).getName();
}
return principal.toString();
}
}

View File

@@ -0,0 +1,149 @@
/*
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.session.security;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.userdetails.User;
import org.springframework.session.ExpiringSession;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.MapSession;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.mock;
import static org.mockito.BDDMockito.verify;
import static org.mockito.BDDMockito.when;
@RunWith(MockitoJUnitRunner.class)
public class SpringSessionBackedSessionRegistryTest {
static final String SESSION_ID = "sessionId";
static final String SESSION_ID2 = "otherSessionId";
static final String USER_NAME = "userName";
static final User PRINCIPAL = new User(USER_NAME, "password", Collections.<GrantedAuthority>emptyList());
static final Date NOW = new Date();
@Mock
FindByIndexNameSessionRepository<ExpiringSession> sessionRepository;
@InjectMocks
SpringSessionBackedSessionRegistry sessionRegistry;
@Test
public void sessionInformationForExistingSession() {
ExpiringSession session = createSession(SESSION_ID, USER_NAME, NOW.getTime());
when(this.sessionRepository.getSession(SESSION_ID)).thenReturn(session);
SessionInformation sessionInfo = this.sessionRegistry.getSessionInformation(SESSION_ID);
assertThat(sessionInfo.getSessionId()).isEqualTo(SESSION_ID);
assertThat(sessionInfo.getLastRequest()).isEqualTo(NOW);
assertThat(sessionInfo.getPrincipal()).isEqualTo(USER_NAME);
assertThat(sessionInfo.isExpired()).isFalse();
}
@Test
public void sessionInformationForExpiredSession() {
ExpiringSession session = createSession(SESSION_ID, USER_NAME, NOW.getTime());
session.setAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR, Boolean.TRUE);
when(this.sessionRepository.getSession(SESSION_ID)).thenReturn(session);
SessionInformation sessionInfo = this.sessionRegistry.getSessionInformation(SESSION_ID);
assertThat(sessionInfo.getSessionId()).isEqualTo(SESSION_ID);
assertThat(sessionInfo.getLastRequest()).isEqualTo(NOW);
assertThat(sessionInfo.getPrincipal()).isEqualTo(USER_NAME);
assertThat(sessionInfo.isExpired()).isTrue();
}
@Test
public void noSessionInformationForMissingSession() {
assertThat(this.sessionRegistry.getSessionInformation("nonExistingSessionId")).isNull();
}
@Test
public void getAllSessions() {
setUpSessions();
List<SessionInformation> allSessionInfos = this.sessionRegistry.getAllSessions(PRINCIPAL, true);
assertThat(allSessionInfos).extracting("sessionId").containsExactly(SESSION_ID, SESSION_ID2);
}
@Test
public void getNonExpiredSessions() {
setUpSessions();
List<SessionInformation> nonExpiredSessionInfos = this.sessionRegistry.getAllSessions(PRINCIPAL, false);
assertThat(nonExpiredSessionInfos).extracting("sessionId").containsExactly(SESSION_ID2);
}
@Test
public void expireNow() {
ExpiringSession session = createSession(SESSION_ID, USER_NAME, NOW.getTime());
when(this.sessionRepository.getSession(SESSION_ID)).thenReturn(session);
SessionInformation sessionInfo = this.sessionRegistry.getSessionInformation(SESSION_ID);
assertThat(sessionInfo.isExpired()).isFalse();
sessionInfo.expireNow();
assertThat(sessionInfo.isExpired()).isTrue();
ArgumentCaptor<ExpiringSession> captor = ArgumentCaptor.forClass(ExpiringSession.class);
verify(this.sessionRepository).save(captor.capture());
assertThat(captor.getValue().getAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR)).isEqualTo(Boolean.TRUE);
}
private ExpiringSession createSession(String sessionId, String userName, Long lastAccessed) {
MapSession session = new MapSession(sessionId);
session.setLastAccessedTime(lastAccessed);
Authentication authentication = mock(Authentication.class);
when(authentication.getName()).thenReturn(userName);
SecurityContextImpl securityContext = new SecurityContextImpl();
securityContext.setAuthentication(authentication);
session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
return session;
}
private void setUpSessions() {
ExpiringSession session1 = createSession(SESSION_ID, USER_NAME, NOW.getTime());
session1.setAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR, Boolean.TRUE);
ExpiringSession session2 = createSession(SESSION_ID2, USER_NAME, NOW.getTime());
Map<String, ExpiringSession> sessions = new LinkedHashMap<String, ExpiringSession>();
sessions.put(session1.getId(), session1);
sessions.put(session2.getId(), session2);
when(this.sessionRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, USER_NAME)).thenReturn(sessions);
}
}