diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 00000000..36717b48 --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,17 @@ + +**Affects:** \ + +--- + diff --git a/.github/actions/dispatch.sh b/.github/actions/dispatch.sh new file mode 100755 index 00000000..d6c2a377 --- /dev/null +++ b/.github/actions/dispatch.sh @@ -0,0 +1,5 @@ +REPOSITORY_REF="$1" +TOKEN="$2" + +curl -H "Accept: application/vnd.github.everest-preview+json" -H "Authorization: token ${TOKEN}" --request POST --data '{"event_type": "request-build"}' https://api.github.com/repos/${REPOSITORY_REF}/dispatches +echo "Requested Build for $REPOSITORY_REF" \ No newline at end of file diff --git a/.github/workflows/build-reference.yml b/.github/workflows/build-reference.yml new file mode 100644 index 00000000..357257fa --- /dev/null +++ b/.github/workflows/build-reference.yml @@ -0,0 +1,27 @@ +name: reference + +on: + push: + branches-ignore: + - 'gh-pages' + +env: + GH_TOKEN_DISPATCH: ${{ secrets.GH_TOKEN_DISPATCH }} + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout Source + uses: actions/checkout@v2 + - name: Generate antora.yml + run: ./gradlew :spring-session-docs:generateAntora + - name: Push generated antora files to the spring-security-docs-generated + uses: JamesIves/github-pages-deploy-action@4.1.4 + with: + branch: "spring-session/main" # The branch the action should deploy to. + folder: "spring-session-docs/build/generateAntora" # The folder the action should deploy. + repository-name: "rwinch/spring-security-docs-generated" + token: ${{ secrets.GH_TOKEN_DISPATCH }} + - name: Dispatch Build Request + run: ${GITHUB_WORKSPACE}/.github/actions/dispatch.sh 'rwinch/spring-reference' "$GH_TOKEN_DISPATCH" diff --git a/.github/workflows/gradle-wrapper-validation.yml b/.github/workflows/gradle-wrapper-validation.yml new file mode 100644 index 00000000..405a2b30 --- /dev/null +++ b/.github/workflows/gradle-wrapper-validation.yml @@ -0,0 +1,10 @@ +name: "Validate Gradle Wrapper" +on: [push, pull_request] + +jobs: + validation: + name: "Validation" + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: gradle/wrapper-validation-action@v1 diff --git a/build.gradle b/build.gradle index fda6edd2..6f4cdbe1 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,7 @@ buildscript { snapshotBuild = version.endsWith('SNAPSHOT') milestoneBuild = !(releaseBuild || snapshotBuild) - springBootVersion = '2.5.3' + springBootVersion = '2.4.5' } repositories { diff --git a/gradle/dependency-management.gradle b/gradle/dependency-management.gradle index 7f4d69dc..8ae033ff 100644 --- a/gradle/dependency-management.gradle +++ b/gradle/dependency-management.gradle @@ -1,6 +1,6 @@ dependencyManagement { imports { - mavenBom 'io.projectreactor:reactor-bom:2020.0.10' + mavenBom 'io.projectreactor:reactor-bom:2020.0.7' mavenBom 'org.junit:junit-bom:5.7.2' mavenBom 'org.springframework:spring-framework-bom:5.3.9' mavenBom 'org.springframework.data:spring-data-bom:2021.1.0-M2' diff --git a/local-antora-playbook.yml b/local-antora-playbook.yml new file mode 100644 index 00000000..2de878a8 --- /dev/null +++ b/local-antora-playbook.yml @@ -0,0 +1,12 @@ +site: + title: Spring Session + start_page: session::index.adoc +content: + sources: + - url: ./ + branches: HEAD + start_path: spring-session-docs +ui: + bundle: + url: ../../rwinch/antora-ui-spring/build/ui-bundle.zip + snapshot: true diff --git a/spring-session-docs/antora.yml b/spring-session-docs/antora.yml new file mode 100644 index 00000000..8fafbdf5 --- /dev/null +++ b/spring-session-docs/antora.yml @@ -0,0 +1,9 @@ +name: session +title: Spring Session +version: ~ +display_version: 2.6 +start_page: ROOT:index.adoc + + +nav: + - modules/ROOT/nav.adoc diff --git a/spring-session-docs/modules/ROOT/examples/java/docs/FindByIndexNameSessionRepositoryTests.java b/spring-session-docs/modules/ROOT/examples/java/docs/FindByIndexNameSessionRepositoryTests.java new file mode 100644 index 00000000..9514987d --- /dev/null +++ b/spring-session-docs/modules/ROOT/examples/java/docs/FindByIndexNameSessionRepositoryTests.java @@ -0,0 +1,63 @@ +/* + * Copyright 2014-2019 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 + * + * https://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; + +import java.util.Map; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import org.springframework.session.FindByIndexNameSessionRepository; +import org.springframework.session.Session; + +/** + * @author Rob Winch + * + */ +class FindByIndexNameSessionRepositoryTests { + + @Mock + FindByIndexNameSessionRepository sessionRepository; + + @Mock + Session session; + + @BeforeEach + void setUp() { + MockitoAnnotations.initMocks(this); + } + + @Test + void setUsername() { + // tag::set-username[] + String username = "username"; + this.session.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username); + // end::set-username[] + } + + @Test + @SuppressWarnings("unused") + void findByUsername() { + // tag::findby-username[] + String username = "username"; + Map sessionIdToSession = this.sessionRepository.findByPrincipalName(username); + // end::findby-username[] + } + +} diff --git a/spring-session-docs/modules/ROOT/examples/java/docs/HttpSessionConfigurationNoOpConfigureRedisActionXmlTests.java b/spring-session-docs/modules/ROOT/examples/java/docs/HttpSessionConfigurationNoOpConfigureRedisActionXmlTests.java new file mode 100644 index 00000000..f3e3d25d --- /dev/null +++ b/spring-session-docs/modules/ROOT/examples/java/docs/HttpSessionConfigurationNoOpConfigureRedisActionXmlTests.java @@ -0,0 +1,53 @@ +/* + * Copyright 2014-2019 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 + * + * https://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; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.session.Session; +import org.springframework.session.web.http.SessionRepositoryFilter; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.context.web.WebAppConfiguration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +/** + * @author Rob Winch + */ +@ExtendWith(SpringExtension.class) +@ContextConfiguration +@WebAppConfiguration +public class HttpSessionConfigurationNoOpConfigureRedisActionXmlTests { + + @Autowired + SessionRepositoryFilter filter; + + @Test + void redisConnectionFactoryNotUsedSinceNoValidation() { + assertThat(this.filter).isNotNull(); + } + + static RedisConnectionFactory connectionFactory() { + return mock(RedisConnectionFactory.class); + } + +} diff --git a/spring-session-docs/modules/ROOT/examples/java/docs/IndexDocTests.java b/spring-session-docs/modules/ROOT/examples/java/docs/IndexDocTests.java new file mode 100644 index 00000000..a9410e66 --- /dev/null +++ b/spring-session-docs/modules/ROOT/examples/java/docs/IndexDocTests.java @@ -0,0 +1,211 @@ +/* + * Copyright 2014-2019 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 + * + * https://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; + +import java.time.Duration; +import java.util.concurrent.ConcurrentHashMap; + +import com.hazelcast.config.Config; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import org.junit.jupiter.api.Test; + +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.ReactiveRedisTemplate; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer; +import org.springframework.data.redis.serializer.RedisSerializationContext; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.mock.web.MockServletContext; +import org.springframework.session.MapSession; +import org.springframework.session.MapSessionRepository; +import org.springframework.session.ReactiveSessionRepository; +import org.springframework.session.Session; +import org.springframework.session.SessionRepository; +import org.springframework.session.data.redis.ReactiveRedisSessionRepository; +import org.springframework.session.data.redis.RedisIndexedSessionRepository; +import org.springframework.session.hazelcast.HazelcastIndexedSessionRepository; +import org.springframework.session.jdbc.JdbcIndexedSessionRepository; +import org.springframework.session.web.http.SessionRepositoryFilter; +import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Rob Winch + * @author Vedran Pavic + */ +class IndexDocTests { + + private static final String ATTR_USER = "user"; + + @Test + void repositoryDemo() { + RepositoryDemo demo = new RepositoryDemo<>(); + demo.repository = new MapSessionRepository(new ConcurrentHashMap<>()); + + demo.demo(); + } + + // tag::repository-demo[] + public class RepositoryDemo { + + private SessionRepository repository; // <1> + + public void demo() { + S toSave = this.repository.createSession(); // <2> + + // <3> + User rwinch = new User("rwinch"); + toSave.setAttribute(ATTR_USER, rwinch); + + this.repository.save(toSave); // <4> + + S session = this.repository.findById(toSave.getId()); // <5> + + // <6> + User user = session.getAttribute(ATTR_USER); + assertThat(user).isEqualTo(rwinch); + } + + // ... setter methods ... + + } + // end::repository-demo[] + + @Test + void expireRepositoryDemo() { + ExpiringRepositoryDemo demo = new ExpiringRepositoryDemo<>(); + demo.repository = new MapSessionRepository(new ConcurrentHashMap<>()); + + demo.demo(); + } + + // tag::expire-repository-demo[] + public class ExpiringRepositoryDemo { + + private SessionRepository repository; // <1> + + public void demo() { + S toSave = this.repository.createSession(); // <2> + // ... + toSave.setMaxInactiveInterval(Duration.ofSeconds(30)); // <3> + + this.repository.save(toSave); // <4> + + S session = this.repository.findById(toSave.getId()); // <5> + // ... + } + + // ... setter methods ... + + } + // end::expire-repository-demo[] + + @Test + @SuppressWarnings("unused") + void newRedisIndexedSessionRepository() { + // tag::new-redisindexedsessionrepository[] + RedisTemplate redisTemplate = new RedisTemplate<>(); + + // ... configure redisTemplate ... + + SessionRepository repository = new RedisIndexedSessionRepository(redisTemplate); + // end::new-redisindexedsessionrepository[] + } + + @Test + @SuppressWarnings("unused") + void newReactiveRedisSessionRepository() { + LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory(); + RedisSerializationContext serializationContext = RedisSerializationContext + .newSerializationContext(new JdkSerializationRedisSerializer()).build(); + + // tag::new-reactiveredissessionrepository[] + // ... create and configure connectionFactory and serializationContext ... + + ReactiveRedisTemplate redisTemplate = new ReactiveRedisTemplate<>(connectionFactory, + serializationContext); + + ReactiveSessionRepository repository = new ReactiveRedisSessionRepository(redisTemplate); + // end::new-reactiveredissessionrepository[] + } + + @Test + @SuppressWarnings("unused") + void mapRepository() { + // tag::new-mapsessionrepository[] + SessionRepository repository = new MapSessionRepository(new ConcurrentHashMap<>()); + // end::new-mapsessionrepository[] + } + + @Test + @SuppressWarnings("unused") + void newJdbcIndexedSessionRepository() { + // tag::new-jdbcindexedsessionrepository[] + JdbcTemplate jdbcTemplate = new JdbcTemplate(); + + // ... configure jdbcTemplate ... + + TransactionTemplate transactionTemplate = new TransactionTemplate(); + + // ... configure transactionTemplate ... + + SessionRepository repository = new JdbcIndexedSessionRepository(jdbcTemplate, + transactionTemplate); + // end::new-jdbcindexedsessionrepository[] + } + + @Test + @SuppressWarnings("unused") + void newHazelcastIndexedSessionRepository() { + // tag::new-hazelcastindexedsessionrepository[] + + Config config = new Config(); + + // ... configure Hazelcast ... + + HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(config); + + HazelcastIndexedSessionRepository repository = new HazelcastIndexedSessionRepository(hazelcastInstance); + // end::new-hazelcastindexedsessionrepository[] + } + + @Test + void runSpringHttpSessionConfig() { + AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); + context.register(SpringHttpSessionConfig.class); + context.setServletContext(new MockServletContext()); + context.refresh(); + + try { + context.getBean(SessionRepositoryFilter.class); + } + finally { + context.close(); + } + } + + private static final class User { + + private User(String username) { + } + + } + +} diff --git a/spring-session-docs/modules/ROOT/examples/java/docs/RedisHttpSessionConfigurationNoOpConfigureRedisActionTests.java b/spring-session-docs/modules/ROOT/examples/java/docs/RedisHttpSessionConfigurationNoOpConfigureRedisActionTests.java new file mode 100644 index 00000000..27b1ebd8 --- /dev/null +++ b/spring-session-docs/modules/ROOT/examples/java/docs/RedisHttpSessionConfigurationNoOpConfigureRedisActionTests.java @@ -0,0 +1,63 @@ +/* + * Copyright 2014-2019 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 + * + * https://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; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.session.data.redis.config.ConfigureRedisAction; +import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.context.web.WebAppConfiguration; + +import static org.mockito.Mockito.mock; + +/** + * @author Rob Winch + */ +@ExtendWith(SpringExtension.class) +@ContextConfiguration +@WebAppConfiguration +class RedisHttpSessionConfigurationNoOpConfigureRedisActionTests { + + @Test + void redisConnectionFactoryNotUsedSinceNoValidation() { + } + + @EnableRedisHttpSession + @Configuration + static class Config { + + // tag::configure-redis-action[] + @Bean + ConfigureRedisAction configureRedisAction() { + return ConfigureRedisAction.NO_OP; + } + // end::configure-redis-action[] + + @Bean + RedisConnectionFactory redisConnectionFactory() { + return mock(RedisConnectionFactory.class); + } + + } + +} diff --git a/spring-session-docs/modules/ROOT/examples/java/docs/SpringHttpSessionConfig.java b/spring-session-docs/modules/ROOT/examples/java/docs/SpringHttpSessionConfig.java new file mode 100644 index 00000000..f257503b --- /dev/null +++ b/spring-session-docs/modules/ROOT/examples/java/docs/SpringHttpSessionConfig.java @@ -0,0 +1,37 @@ +/* + * Copyright 2014-2019 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 + * + * https://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; + +import java.util.concurrent.ConcurrentHashMap; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.session.MapSessionRepository; +import org.springframework.session.config.annotation.web.http.EnableSpringHttpSession; + +// tag::class[] +@EnableSpringHttpSession +@Configuration +public class SpringHttpSessionConfig { + + @Bean + public MapSessionRepository sessionRepository() { + return new MapSessionRepository(new ConcurrentHashMap<>()); + } + +} +// end::class[] diff --git a/spring-session-docs/modules/ROOT/examples/java/docs/SpringWebSessionConfig.java b/spring-session-docs/modules/ROOT/examples/java/docs/SpringWebSessionConfig.java new file mode 100644 index 00000000..69e22fca --- /dev/null +++ b/spring-session-docs/modules/ROOT/examples/java/docs/SpringWebSessionConfig.java @@ -0,0 +1,36 @@ +/* + * Copyright 2014-2019 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 + * + * https://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; + +import java.util.concurrent.ConcurrentHashMap; + +import org.springframework.context.annotation.Bean; +import org.springframework.session.ReactiveMapSessionRepository; +import org.springframework.session.ReactiveSessionRepository; +import org.springframework.session.config.annotation.web.server.EnableSpringWebSession; + +// tag::class[] +@EnableSpringWebSession +public class SpringWebSessionConfig { + + @Bean + public ReactiveSessionRepository reactiveSessionRepository() { + return new ReactiveMapSessionRepository(new ConcurrentHashMap<>()); + } + +} +// end::class[] diff --git a/spring-session-docs/modules/ROOT/examples/java/docs/http/AbstractHttpSessionListenerTests.java b/spring-session-docs/modules/ROOT/examples/java/docs/http/AbstractHttpSessionListenerTests.java new file mode 100644 index 00000000..4b5047f8 --- /dev/null +++ b/spring-session-docs/modules/ROOT/examples/java/docs/http/AbstractHttpSessionListenerTests.java @@ -0,0 +1,94 @@ +/* + * Copyright 2014-2019 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 + * + * https://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.http; + +import java.util.Properties; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.context.ApplicationListener; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.security.core.session.SessionDestroyedEvent; +import org.springframework.session.MapSession; +import org.springframework.session.Session; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.context.web.WebAppConfiguration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + +/** + * @author Rob Winch + * @author Mark Paluch + * @since 1.2 + */ +@ExtendWith(SpringExtension.class) +@WebAppConfiguration +public abstract class AbstractHttpSessionListenerTests { + + @Autowired + ApplicationEventPublisher publisher; + + @Autowired + SecuritySessionDestroyedListener listener; + + @Test + void springSessionDestroyedTranslatedToSpringSecurityDestroyed() { + Session session = new MapSession(); + + this.publisher.publishEvent(new org.springframework.session.events.SessionDestroyedEvent(this, session)); + + assertThat(this.listener.getEvent().getId()).isEqualTo(session.getId()); + } + + static RedisConnectionFactory createMockRedisConnection() { + RedisConnectionFactory factory = mock(RedisConnectionFactory.class); + RedisConnection connection = mock(RedisConnection.class); + + given(factory.getConnection()).willReturn(connection); + given(connection.getConfig(anyString())).willReturn(new Properties()); + return factory; + } + + static class SecuritySessionDestroyedListener implements ApplicationListener { + + private SessionDestroyedEvent event; + + /* + * (non-Javadoc) + * + * @see org.springframework.context.ApplicationListener#onApplicationEvent(org. + * springframework.context.ApplicationEvent) + */ + @Override + public void onApplicationEvent(SessionDestroyedEvent event) { + this.event = event; + } + + SessionDestroyedEvent getEvent() { + return this.event; + } + + } + +} diff --git a/spring-session-docs/modules/ROOT/examples/java/docs/http/HazelcastHttpSessionConfig.java b/spring-session-docs/modules/ROOT/examples/java/docs/http/HazelcastHttpSessionConfig.java new file mode 100644 index 00000000..c77bc1d3 --- /dev/null +++ b/spring-session-docs/modules/ROOT/examples/java/docs/http/HazelcastHttpSessionConfig.java @@ -0,0 +1,55 @@ +/* + * Copyright 2014-2019 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 + * + * https://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.http; + +import com.hazelcast.config.Config; +import com.hazelcast.config.MapAttributeConfig; +import com.hazelcast.config.MapIndexConfig; +import com.hazelcast.config.SerializerConfig; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.session.MapSession; +import org.springframework.session.hazelcast.HazelcastIndexedSessionRepository; +import org.springframework.session.hazelcast.HazelcastSessionSerializer; +import org.springframework.session.hazelcast.PrincipalNameExtractor; +import org.springframework.session.hazelcast.config.annotation.web.http.EnableHazelcastHttpSession; + +//tag::config[] +@EnableHazelcastHttpSession // <1> +@Configuration +public class HazelcastHttpSessionConfig { + + @Bean + public HazelcastInstance hazelcastInstance() { + Config config = new Config(); + MapAttributeConfig attributeConfig = new MapAttributeConfig() + .setName(HazelcastIndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE) + .setExtractor(PrincipalNameExtractor.class.getName()); + config.getMapConfig(HazelcastIndexedSessionRepository.DEFAULT_SESSION_MAP_NAME) // <2> + .addMapAttributeConfig(attributeConfig).addMapIndexConfig( + new MapIndexConfig(HazelcastIndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE, false)); + SerializerConfig serializerConfig = new SerializerConfig(); + serializerConfig.setImplementation(new HazelcastSessionSerializer()).setTypeClass(MapSession.class); + config.getSerializationConfig().addSerializerConfig(serializerConfig); // <3> + return Hazelcast.newHazelcastInstance(config); // <4> + } + +} +// end::config[] diff --git a/spring-session-docs/modules/ROOT/examples/java/docs/http/HttpSessionListenerJavaConfigTests.java b/spring-session-docs/modules/ROOT/examples/java/docs/http/HttpSessionListenerJavaConfigTests.java new file mode 100644 index 00000000..e47bb696 --- /dev/null +++ b/spring-session-docs/modules/ROOT/examples/java/docs/http/HttpSessionListenerJavaConfigTests.java @@ -0,0 +1,46 @@ +/* + * Copyright 2014-2019 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 + * + * https://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.http; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.test.context.ContextConfiguration; + +/** + * @author Rob Winch + * + */ +@ContextConfiguration(classes = { HttpSessionListenerJavaConfigTests.MockConfig.class, RedisHttpSessionConfig.class }) +class HttpSessionListenerJavaConfigTests extends AbstractHttpSessionListenerTests { + + @Configuration + static class MockConfig { + + @Bean + static RedisConnectionFactory redisConnectionFactory() { + return AbstractHttpSessionListenerTests.createMockRedisConnection(); + } + + @Bean + SecuritySessionDestroyedListener securitySessionDestroyedListener() { + return new SecuritySessionDestroyedListener(); + } + + } + +} diff --git a/spring-session-docs/src/main/java/docs/Docs.java b/spring-session-docs/modules/ROOT/examples/java/docs/http/HttpSessionListenerXmlTests.java similarity index 74% rename from spring-session-docs/src/main/java/docs/Docs.java rename to spring-session-docs/modules/ROOT/examples/java/docs/http/HttpSessionListenerXmlTests.java index 3d4f665f..c6c89d67 100644 --- a/spring-session-docs/src/main/java/docs/Docs.java +++ b/spring-session-docs/modules/ROOT/examples/java/docs/http/HttpSessionListenerXmlTests.java @@ -14,8 +14,15 @@ * limitations under the License. */ -package docs; +package docs.http; -public class Docs { +import org.springframework.test.context.ContextConfiguration; + +/** + * @author Rob Winch + * + */ +@ContextConfiguration +class HttpSessionListenerXmlTests extends AbstractHttpSessionListenerTests { } diff --git a/spring-session-docs/modules/ROOT/examples/java/docs/http/RedisHttpSessionConfig.java b/spring-session-docs/modules/ROOT/examples/java/docs/http/RedisHttpSessionConfig.java new file mode 100644 index 00000000..85caeb48 --- /dev/null +++ b/spring-session-docs/modules/ROOT/examples/java/docs/http/RedisHttpSessionConfig.java @@ -0,0 +1,37 @@ +/* + * Copyright 2014-2019 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 + * + * https://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.http; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.web.session.HttpSessionEventPublisher; +import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; + +// tag::config[] +@Configuration +@EnableRedisHttpSession +public class RedisHttpSessionConfig { + + @Bean + public HttpSessionEventPublisher httpSessionEventPublisher() { + return new HttpSessionEventPublisher(); + } + + // ... + +} +// end::config[] diff --git a/spring-session-docs/modules/ROOT/examples/java/docs/security/RememberMeSecurityConfiguration.java b/spring-session-docs/modules/ROOT/examples/java/docs/security/RememberMeSecurityConfiguration.java new file mode 100644 index 00000000..d8061e30 --- /dev/null +++ b/spring-session-docs/modules/ROOT/examples/java/docs/security/RememberMeSecurityConfiguration.java @@ -0,0 +1,82 @@ +/* + * Copyright 2014-2019 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 + * + * https://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 java.util.concurrent.ConcurrentHashMap; + +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.Customizer; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.provisioning.InMemoryUserDetailsManager; +import org.springframework.session.MapSessionRepository; +import org.springframework.session.config.annotation.web.http.EnableSpringHttpSession; +import org.springframework.session.security.web.authentication.SpringSessionRememberMeServices; + +/** + * @author rwinch + */ +@EnableWebSecurity +@EnableSpringHttpSession +public class RememberMeSecurityConfiguration extends WebSecurityConfigurerAdapter { + + // @formatter:off + // tag::http-rememberme[] + @Override + protected void configure(HttpSecurity http) throws Exception { + http + // ... additional configuration ... + .rememberMe((rememberMe) -> rememberMe + .rememberMeServices(rememberMeServices()) + ); + // end::http-rememberme[] + + http + .formLogin(Customizer.withDefaults()) + .authorizeRequests((authorize) -> authorize + .anyRequest().authenticated() + ); + } + + // tag::rememberme-bean[] + @Bean + public SpringSessionRememberMeServices rememberMeServices() { + SpringSessionRememberMeServices rememberMeServices = + new SpringSessionRememberMeServices(); + // optionally customize + rememberMeServices.setAlwaysRemember(true); + return rememberMeServices; + } + // end::rememberme-bean[] + // @formatter:on + + @Override + @Bean + public InMemoryUserDetailsManager userDetailsService() { + return new InMemoryUserDetailsManager( + User.withUsername("user").password("{noop}password").roles("USER").build()); + } + + @Bean + MapSessionRepository sessionRepository() { + return new MapSessionRepository(new ConcurrentHashMap<>()); + } + +} +// end::class[] diff --git a/spring-session-docs/modules/ROOT/examples/java/docs/security/RememberMeSecurityConfigurationTests.java b/spring-session-docs/modules/ROOT/examples/java/docs/security/RememberMeSecurityConfigurationTests.java new file mode 100644 index 00000000..3fb66778 --- /dev/null +++ b/spring-session-docs/modules/ROOT/examples/java/docs/security/RememberMeSecurityConfigurationTests.java @@ -0,0 +1,92 @@ +/* + * Copyright 2014-2019 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 + * + * https://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 java.time.Duration; +import java.util.Base64; + +import javax.servlet.http.Cookie; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.session.Session; +import org.springframework.session.SessionRepository; +import org.springframework.session.web.http.SessionRepositoryFilter; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; + +/** + * @author rwinch + * @author Vedran Pavic + */ +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = RememberMeSecurityConfiguration.class) +@WebAppConfiguration +@SuppressWarnings("rawtypes") +class RememberMeSecurityConfigurationTests { + + @Autowired + WebApplicationContext context; + + @Autowired + SessionRepositoryFilter springSessionRepositoryFilter; + + @Autowired + SessionRepository sessions; + + private MockMvc mockMvc; + + @BeforeEach + void setup() { + // @formatter:off + this.mockMvc = MockMvcBuilders + .webAppContextSetup(this.context) + .addFilters(this.springSessionRepositoryFilter) + .apply(springSecurity()) + .build(); + // @formatter:on + } + + @Test + void authenticateWhenSpringSessionRememberMeEnabledThenCookieMaxAgeAndSessionExpirationSet() throws Exception { + // @formatter:off + MvcResult result = this.mockMvc + .perform(formLogin()) + .andReturn(); + // @formatter:on + + Cookie cookie = result.getResponse().getCookie("SESSION"); + assertThat(cookie.getMaxAge()).isEqualTo(Integer.MAX_VALUE); + T session = this.sessions.findById(new String(Base64.getDecoder().decode(cookie.getValue()))); + assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ofDays(30)); + + } + +} +// end::class[] diff --git a/spring-session-docs/modules/ROOT/examples/java/docs/security/RememberMeSecurityConfigurationXmlTests.java b/spring-session-docs/modules/ROOT/examples/java/docs/security/RememberMeSecurityConfigurationXmlTests.java new file mode 100644 index 00000000..91c99651 --- /dev/null +++ b/spring-session-docs/modules/ROOT/examples/java/docs/security/RememberMeSecurityConfigurationXmlTests.java @@ -0,0 +1,92 @@ +/* + * Copyright 2014-2019 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 + * + * https://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 java.time.Duration; +import java.util.Base64; + +import javax.servlet.http.Cookie; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.session.Session; +import org.springframework.session.SessionRepository; +import org.springframework.session.web.http.SessionRepositoryFilter; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; + +/** + * @author rwinch + * @author Vedran Pavic + */ +@ExtendWith(SpringExtension.class) +@ContextConfiguration +@WebAppConfiguration +@SuppressWarnings("rawtypes") +class RememberMeSecurityConfigurationXmlTests { + + @Autowired + WebApplicationContext context; + + @Autowired + SessionRepositoryFilter springSessionRepositoryFilter; + + @Autowired + SessionRepository sessions; + + private MockMvc mockMvc; + + @BeforeEach + void setup() { + // @formatter:off + this.mockMvc = MockMvcBuilders + .webAppContextSetup(this.context) + .addFilters(this.springSessionRepositoryFilter) + .apply(springSecurity()) + .build(); + // @formatter:on + } + + @Test + void authenticateWhenSpringSessionRememberMeEnabledThenCookieMaxAgeAndSessionExpirationSet() throws Exception { + // @formatter:off + MvcResult result = this.mockMvc + .perform(formLogin()) + .andReturn(); + // @formatter:on + + Cookie cookie = result.getResponse().getCookie("SESSION"); + assertThat(cookie.getMaxAge()).isEqualTo(Integer.MAX_VALUE); + T session = this.sessions.findById(new String(Base64.getDecoder().decode(cookie.getValue()))); + assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ofDays(30)); + + } + +} +// end::class[] diff --git a/spring-session-docs/modules/ROOT/examples/java/docs/security/SecurityConfiguration.java b/spring-session-docs/modules/ROOT/examples/java/docs/security/SecurityConfiguration.java new file mode 100644 index 00000000..a5498bd0 --- /dev/null +++ b/spring-session-docs/modules/ROOT/examples/java/docs/security/SecurityConfiguration.java @@ -0,0 +1,56 @@ +/* + * Copyright 2014-2019 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 + * + * https://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.FindByIndexNameSessionRepository; +import org.springframework.session.Session; +import org.springframework.session.security.SpringSessionBackedSessionRegistry; + +/** + * @author Joris Kuipers + */ +// tag::class[] +@Configuration +public class SecurityConfiguration extends WebSecurityConfigurerAdapter { + + @Autowired + private FindByIndexNameSessionRepository sessionRepository; + + @Override + protected void configure(HttpSecurity http) throws Exception { + // @formatter:off + http + // other config goes here... + .sessionManagement((sessionManagement) -> sessionManagement + .maximumSessions(2) + .sessionRegistry(sessionRegistry()) + ); + // @formatter:on + } + + @Bean + public SpringSessionBackedSessionRegistry sessionRegistry() { + return new SpringSessionBackedSessionRegistry<>(this.sessionRepository); + } + +} +// end::class[] diff --git a/spring-session-docs/modules/ROOT/examples/java/docs/websocket/WebSocketConfig.java b/spring-session-docs/modules/ROOT/examples/java/docs/websocket/WebSocketConfig.java new file mode 100644 index 00000000..92e07ef5 --- /dev/null +++ b/spring-session-docs/modules/ROOT/examples/java/docs/websocket/WebSocketConfig.java @@ -0,0 +1,47 @@ +/* + * Copyright 2014-2019 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 + * + * https://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.websocket; + +import org.springframework.context.annotation.Configuration; +import org.springframework.messaging.simp.config.MessageBrokerRegistry; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; +import org.springframework.web.socket.config.annotation.StompEndpointRegistry; +import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; + +/** + * @author Rob Winch + */ +// tag::class[] +@Configuration +@EnableScheduling +@EnableWebSocketMessageBroker +public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { + + @Override + public void registerStompEndpoints(StompEndpointRegistry registry) { + registry.addEndpoint("/messages").withSockJS(); + } + + @Override + public void configureMessageBroker(MessageBrokerRegistry registry) { + registry.enableSimpleBroker("/queue/", "/topic/"); + registry.setApplicationDestinationPrefixes("/app"); + } + +} +// end::class[] diff --git a/spring-session-docs/modules/ROOT/examples/resources/docs/HttpSessionConfigurationNoOpConfigureRedisActionXmlTests-context.xml b/spring-session-docs/modules/ROOT/examples/resources/docs/HttpSessionConfigurationNoOpConfigureRedisActionXmlTests-context.xml new file mode 100644 index 00000000..631a86dd --- /dev/null +++ b/spring-session-docs/modules/ROOT/examples/resources/docs/HttpSessionConfigurationNoOpConfigureRedisActionXmlTests-context.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + diff --git a/spring-session-docs/modules/ROOT/examples/resources/docs/http/HttpSessionListenerXmlTests-context.xml b/spring-session-docs/modules/ROOT/examples/resources/docs/http/HttpSessionListenerXmlTests-context.xml new file mode 100644 index 00000000..aafcaa6e --- /dev/null +++ b/spring-session-docs/modules/ROOT/examples/resources/docs/http/HttpSessionListenerXmlTests-context.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + diff --git a/spring-session-docs/modules/ROOT/examples/resources/docs/security/RememberMeSecurityConfigurationXmlTests-context.xml b/spring-session-docs/modules/ROOT/examples/resources/docs/security/RememberMeSecurityConfigurationXmlTests-context.xml new file mode 100644 index 00000000..1996c58f --- /dev/null +++ b/spring-session-docs/modules/ROOT/examples/resources/docs/security/RememberMeSecurityConfigurationXmlTests-context.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-session-docs/modules/ROOT/examples/resources/docs/security/security-config.xml b/spring-session-docs/modules/ROOT/examples/resources/docs/security/security-config.xml new file mode 100644 index 00000000..42a5a4a3 --- /dev/null +++ b/spring-session-docs/modules/ROOT/examples/resources/docs/security/security-config.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + diff --git a/spring-session-docs/modules/ROOT/examples/session-jdbc-main-resources-dir b/spring-session-docs/modules/ROOT/examples/session-jdbc-main-resources-dir new file mode 120000 index 00000000..1a4b1f19 --- /dev/null +++ b/spring-session-docs/modules/ROOT/examples/session-jdbc-main-resources-dir @@ -0,0 +1 @@ +../../../../spring-session-jdbc/src/main/resources \ No newline at end of file diff --git a/spring-session-docs/modules/ROOT/examples/spring-session-samples b/spring-session-docs/modules/ROOT/examples/spring-session-samples new file mode 120000 index 00000000..09f8f267 --- /dev/null +++ b/spring-session-docs/modules/ROOT/examples/spring-session-samples @@ -0,0 +1 @@ +../../../../spring-session-samples \ No newline at end of file diff --git a/spring-session-docs/modules/ROOT/nav.adoc b/spring-session-docs/modules/ROOT/nav.adoc new file mode 100644 index 00000000..d7dc5a60 --- /dev/null +++ b/spring-session-docs/modules/ROOT/nav.adoc @@ -0,0 +1,24 @@ +* xref:whats-new.adoc[What's New] +* xref:samples.adoc[Samples & Guides (Start Here)] +** Boot Samples +*** HttpSession +**** Redis +***** {gh-samples-url}spring-session-sample-boot-redis-json[JSON serialization] +***** {gh-samples-url}spring-session-sample-boot-redis-simple[Simple Redis] +***** xref:guides/boot-redis.adoc[Redis with Events] +**** xref:guides/boot-jdbc.adoc[JDBC] +**** {gh-samples-url}spring-session-sample-boot-hazelcast[HttpSession with Hazelcast] +*** xref:guides/boot-findbyusername.adoc[Find by Username] +*** xref:guides/boot-websocket.adoc[WebSockets] +** WebFlux +*** {gh-samples-url}spring-session-sample-boot-webflux[Redis] +*** xref:guides/boot-webflux-custom-cookie.adoc[Custom Cookie] +** Java Configuration +** XML Configuration +* xref:modules.adoc[Modules] +* xref:http-session.adoc[HttpSession Integration] +* xref:web-socket.adoc[WebSocket Integration] +* xref:web-session.adoc[WebSession Integration] +* xref:spring-security.adoc[Spring Security Integration] +* xref:api.adoc[API Documentation] +* xref:upgrading.adoc[Upgrading] diff --git a/spring-session-docs/src/docs/asciidoc/index.adoc b/spring-session-docs/modules/ROOT/pages/api.adoc similarity index 50% rename from spring-session-docs/src/docs/asciidoc/index.adoc rename to spring-session-docs/modules/ROOT/pages/api.adoc index 21fdcca1..b8fe0469 100644 --- a/spring-session-docs/src/docs/asciidoc/index.adoc +++ b/spring-session-docs/modules/ROOT/pages/api.adoc @@ -1,585 +1,5 @@ -= Spring Session -Rob Winch; Vedran Pavić; Jay Bryant; Eleftheria Stein-Kousathana -:doctype: book -:indexdoc-tests: {docs-test-dir}docs/IndexDocTests.java -:websocketdoc-test-dir: {docs-test-dir}docs/websocket/ -:toc: left - -ifdef::backend-html5[] -NOTE: This documentation is also available as https://docs.spring.io/spring-session/docs/{spring-session-version}/reference/pdf/spring-session-reference.pdf[PDF]. -endif::[] - -ifdef::backend-pdf[] -NOTE: This documentation is also available as https://docs.spring.io/spring-session/docs/{spring-session-version}/reference/html5/index.html[HTML]. -endif::[] - -[[abstract]] -Spring Session provides an API and implementations for managing a user's session information. - -[[introduction]] -== Introduction - -Spring Session provides an API and implementations for managing a user's session information while also making it trivial to support clustered sessions without being tied to an application container-specific solution. -It also provides transparent integration with: - -* <>: Allows replacing the `HttpSession` in an application container-neutral way, with support for providing session IDs in headers to work with RESTful APIs. -* <>: Provides the ability to keep the `HttpSession` alive when receiving WebSocket messages -* <>: Allows replacing the Spring WebFlux's `WebSession` in an application container-neutral way. - -== What's New - -Check also the Spring Session BOM https://github.com/spring-projects/spring-session-bom/wiki#release-notes[release notes] -for a list of new and noteworthy features, as well as upgrade instructions for each release. - -[[samples]] -== Samples and Guides (Start Here) - -To get started with Spring Session, the best place to start is our Sample Applications. - -.Sample Applications that use Spring Boot -|=== -| Source | Description | Guide - -| {gh-samples-url}spring-session-sample-boot-redis[HttpSession with Redis] -| Demonstrates how to use Spring Session to replace the `HttpSession` with Redis. -| link:guides/boot-redis.html[HttpSession with Redis Guide] - -| {gh-samples-url}spring-session-sample-boot-jdbc[HttpSession with JDBC] -| Demonstrates how to use Spring Session to replace the `HttpSession` with a relational database store. -| link:guides/boot-jdbc.html[HttpSession with JDBC Guide] - -| {gh-samples-url}spring-session-sample-boot-hazelcast[HttpSession with Hazelcast] -| Demonstrates how to use Spring Session to replace the `HttpSession` with Hazelcast. -| - -| {gh-samples-url}spring-session-sample-boot-findbyusername[Find by Username] -| Demonstrates how to use Spring Session to find sessions by username. -| link:guides/boot-findbyusername.html[Find by Username Guide] - -| {gh-samples-url}spring-session-sample-boot-websocket[WebSockets] -| Demonstrates how to use Spring Session with WebSockets. -| link:guides/boot-websocket.html[WebSockets Guide] - -| {gh-samples-url}spring-session-sample-boot-webflux[WebFlux] -| Demonstrates how to use Spring Session to replace the Spring WebFlux's `WebSession` with Redis. -| - -| {gh-samples-url}spring-session-sample-boot-webflux-custom-cookie[WebFlux with Custom Cookie] -| Demonstrates how to use Spring Session to customize the Session cookie in a WebFlux based application. -| link:guides/boot-webflux-custom-cookie.html[WebFlux with Custom Cookie Guide] - -| {gh-samples-url}spring-session-sample-boot-redis-json[HttpSession with Redis JSON serialization] -| Demonstrates how to use Spring Session to replace the `HttpSession` with Redis using JSON serialization. -| - -| {gh-samples-url}spring-session-sample-boot-redis-simple[HttpSession with simple Redis `SessionRepository`] -| Demonstrates how to use Spring Session to replace the `HttpSession` with Redis using `RedisSessionRepository`. -| - -|=== - -.Sample Applications that use Spring Java-based configuration -|=== -| Source | Description | Guide - -| {gh-samples-url}spring-session-sample-javaconfig-redis[HttpSession with Redis] -| Demonstrates how to use Spring Session to replace the `HttpSession` with Redis. -| link:guides/java-redis.html[HttpSession with Redis Guide] - -| {gh-samples-url}spring-session-sample-javaconfig-jdbc[HttpSession with JDBC] -| Demonstrates how to use Spring Session to replace the `HttpSession` with a relational database store. -| link:guides/java-jdbc.html[HttpSession with JDBC Guide] - -| {gh-samples-url}spring-session-sample-javaconfig-hazelcast[HttpSession with Hazelcast] -| Demonstrates how to use Spring Session to replace the `HttpSession` with Hazelcast. -| link:guides/java-hazelcast.html[HttpSession with Hazelcast Guide] - -| {gh-samples-url}spring-session-sample-javaconfig-custom-cookie[Custom Cookie] -| Demonstrates how to use Spring Session and customize the cookie. -| link:guides/java-custom-cookie.html[Custom Cookie Guide] - -| {gh-samples-url}spring-session-sample-javaconfig-security[Spring Security] -| Demonstrates how to use Spring Session with an existing Spring Security application. -| link:guides/java-security.html[Spring Security Guide] - -| {gh-samples-url}spring-session-sample-javaconfig-rest[REST] -| Demonstrates how to use Spring Session in a REST application to support authenticating with a header. -| link:guides/java-rest.html[REST Guide] - -|=== - -.Sample Applications that use Spring XML-based configuration -|=== -| Source | Description | Guide - -| {gh-samples-url}spring-session-sample-xml-redis[HttpSession with Redis] -| Demonstrates how to use Spring Session to replace the `HttpSession` with a Redis store. -| link:guides/xml-redis.html[HttpSession with Redis Guide] - -| {gh-samples-url}spring-session-sample-xml-jdbc[HttpSession with JDBC] -| Demonstrates how to use Spring Session to replace the `HttpSession` with a relational database store. -| link:guides/xml-jdbc.html[HttpSession with JDBC Guide] - -|=== - -.Miscellaneous sample Applications -|=== -| Source | Description | Guide - -| {gh-samples-url}spring-session-sample-misc-hazelcast[Hazelcast] -| Demonstrates how to use Spring Session with Hazelcast in a Java EE application. -| - -|=== - -[[modules]] -== Spring Session Modules - -In Spring Session 1.x, all of the Spring Session's `SessionRepository` implementations were available within the `spring-session` artifact. -While convenient, this approach was not sustainable long-term as more features and `SessionRepository` implementations were added to the project. - -Starting with Spring Session 2.0, the project has been split into Spring Session Core module and several other modules that carry `SessionRepository` implementations and functionality related to the specific data store. -Users of Spring Data should find this arrangement familiar, with Spring Session Core module taking a role equivalent to Spring Data Commons and providing core functionalities and APIs, with other modules containing data store specific implementations. -As part of this split, the Spring Session Data MongoDB and Spring Session Data GemFire modules were moved to separate repositories. -Now the situation with project's repositories/modules is as follows: - -* https://github.com/spring-projects/spring-session[`spring-session` repository] -** Hosts the Spring Session Core, Spring Session Data Redis, Spring Session JDBC, and Spring Session Hazelcast modules -* https://github.com/spring-projects/spring-session-data-mongodb[`spring-session-data-mongodb` repository] -** Hosts the Spring Session Data MongoDB module. Spring Session Data MongoDB has its own user guide, which you can find at the [https://spring.io/projects/spring-session-data-mongodb#learnSpring site]. - -* https://github.com/spring-projects/spring-session-data-geode[`spring-session-data-geode` repository] -** Hosts the Spring Session Data Geode modules. Spring Session Data Geode has its own user guide, which you can find at the [https://spring.io/projects/spring-session-data-geode#learn site]. - -Finally, Spring Session now also provides a Maven BOM ("`bill of materials`") module in order to help users with version management concerns: - -* https://github.com/spring-projects/spring-session-bom[`spring-session-bom` repository] -** Hosts the Spring Session BOM module - -[[httpsession]] -== `HttpSession` Integration - -Spring Session provides transparent integration with `HttpSession`. -This means that developers can switch the `HttpSession` implementation out with an implementation that is backed by Spring Session. - -[[httpsession-why]] -=== Why Spring Session and `HttpSession`? - -We have already mentioned that Spring Session provides transparent integration with `HttpSession`, but what benefits do we get out of this? - -* *Clustered Sessions*: Spring Session makes it trivial to support <> without being tied to an application container specific solution. -* *RESTful APIs*: Spring Session lets providing session IDs in headers work with <> - -[[httpsession-redis]] -=== `HttpSession` with Redis - -Using Spring Session with `HttpSession` is enabled by adding a Servlet Filter before anything that uses the `HttpSession`. -You can choose from enabling this by using either: - -* <> -* <> - -[[httpsession-redis-jc]] -==== Redis Java-based Configuration - -This section describes how to use Redis to back `HttpSession` by using Java based configuration. - -NOTE: The <> provides a working sample of how to integrate Spring Session and `HttpSession` by using Java configuration. -You can read the basic steps for integration in the next few sections, but we encourage you to follow along with the detailed HttpSession Guide when integrating with your own application. - -include::guides/java-redis.adoc[tags=config,leveloffset=+3] - -[[httpsession-redis-xml]] -==== Redis XML-based Configuration - -This section describes how to use Redis to back `HttpSession` by using XML based configuration. - -NOTE: The <> provides a working sample of how to integrate Spring Session and `HttpSession` using XML configuration. -You can read the basic steps for integration in the next few sections, but we encourage you to follow along with the detailed HttpSession XML Guide when integrating with your own application. - -include::guides/xml-redis.adoc[tags=config,leveloffset=+3] - -[[httpsession-jdbc]] -=== `HttpSession` with JDBC - -You can use Spring Session with `HttpSession` by adding a servlet filter before anything that uses the `HttpSession`. -You can choose to do in any of the following ways: - -* <> -* <> -* <> - -[[httpsession-jdbc-jc]] -==== JDBC Java-based Configuration - -This section describes how to use a relational database to back `HttpSession` when you use Java-based configuration. - -NOTE: The <> provides a working sample of how to integrate Spring Session and `HttpSession` by using Java configuration. -You can read the basic steps for integration in the next few sections, but we encouraged you to follow along with the detailed HttpSession JDBC Guide when integrating with your own application. - -include::guides/java-jdbc.adoc[tags=config,leveloffset=+3] - -[[httpsession-jdbc-xml]] -==== JDBC XML-based Configuration - -This section describes how to use a relational database to back `HttpSession` when you use XML based configuration. - -NOTE: The <> provides a working sample of how to integrate Spring Session and `HttpSession` by using XML configuration. -You can read the basic steps for integration in the next few sections, but we encourage you to follow along with the detailed HttpSession JDBC XML Guide when integrating with your own application. - -include::guides/xml-jdbc.adoc[tags=config,leveloffset=+3] - -[[httpsession-jdbc-boot]] -==== JDBC Spring Boot-based Configuration - -This section describes how to use a relational database to back `HttpSession` when you use Spring Boot. - -NOTE: The <> provides a working sample of how to integrate Spring Session and `HttpSession` by using Spring Boot. -You can read the basic steps for integration in the next few sections, but we encourage you to follow along with the detailed HttpSession JDBC Spring Boot Guide when integrating with your own application. - -include::guides/boot-jdbc.adoc[tags=config,leveloffset=+3] - -[[httpsession-hazelcast]] -=== HttpSession with Hazelcast - -Using Spring Session with `HttpSession` is enabled by adding a Servlet Filter before anything that uses the `HttpSession`. - -This section describes how to use Hazelcast to back `HttpSession` by using Java-based configuration. - -NOTE: The <> provides a working sample of how to integrate Spring Session and `HttpSession` by using Java configuration. -You can read the basic steps for integration in the next few sections, but we encourage you to follow along with the detailed Hazelcast Spring Guide when integrating with your own application. - -include::guides/java-hazelcast.adoc[tags=config,leveloffset=+2] - -[[httpsession-how]] -=== How `HttpSession` Integration Works - -Fortunately, both `HttpSession` and `HttpServletRequest` (the API for obtaining an `HttpSession`) are both interfaces. -This means that we can provide our own implementations for each of these APIs. - -NOTE: This section describes how Spring Session provides transparent integration with `HttpSession`. We offer this content so that you can understand what is happening under the covers. This functionality is already integrated and you do NOT need to implement this logic yourself. - -First, we create a custom `HttpServletRequest` that returns a custom implementation of `HttpSession`. -It looks something like the following: - -==== -[source, java] ----- -public class SessionRepositoryRequestWrapper extends HttpServletRequestWrapper { - - public SessionRepositoryRequestWrapper(HttpServletRequest original) { - super(original); - } - - public HttpSession getSession() { - return getSession(true); - } - - public HttpSession getSession(boolean createNew) { - // create an HttpSession implementation from Spring Session - } - - // ... other methods delegate to the original HttpServletRequest ... -} ----- -==== - -Any method that returns an `HttpSession` is overridden. -All other methods are implemented by `HttpServletRequestWrapper` and delegate to the original `HttpServletRequest` implementation. - -We replace the `HttpServletRequest` implementation by using a servlet `Filter` called `SessionRepositoryFilter`. -The following pseudocode shows how it works: - -==== -[source, java] ----- -public class SessionRepositoryFilter implements Filter { - - public doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { - HttpServletRequest httpRequest = (HttpServletRequest) request; - SessionRepositoryRequestWrapper customRequest = - new SessionRepositoryRequestWrapper(httpRequest); - - chain.doFilter(customRequest, response, chain); - } - - // ... -} ----- -==== - -By passing a custom `HttpServletRequest` implementation into the `FilterChain`, we ensure that anything invoked after our `Filter` uses the custom `HttpSession` implementation. -This highlights why it is important that Spring Session's `SessionRepositoryFilter` be placed before anything that interacts with the `HttpSession`. - -[[httpsession-rest]] -=== `HttpSession` and RESTful APIs - -Spring Session can work with RESTful APIs by letting the session be provided in a header. - -NOTE: The <> provides a working sample of how to use Spring Session in a REST application to support authenticating with a header. -You can follow the basic steps for integration described in the next few sections, but we encourage you to follow along with the detailed REST Guide when integrating with your own application. - -include::guides/java-rest.adoc[tags=config,leveloffset=+2] - -[[httpsession-httpsessionlistener]] -=== Using `HttpSessionListener` - -Spring Session supports `HttpSessionListener` by translating `SessionDestroyedEvent` and `SessionCreatedEvent` into `HttpSessionEvent` by declaring `SessionEventHttpSessionListenerAdapter`. -To use this support, you need to: - -* Ensure your `SessionRepository` implementation supports and is configured to fire `SessionDestroyedEvent` and `SessionCreatedEvent`. -* Configure `SessionEventHttpSessionListenerAdapter` as a Spring bean. -* Inject every `HttpSessionListener` into the `SessionEventHttpSessionListenerAdapter` - -If you use the configuration support documented in <>, all you need to do is register every `HttpSessionListener` as a bean. -For example, assume you want to support Spring Security's concurrency control and need to use `HttpSessionEventPublisher`. In that case, you can add `HttpSessionEventPublisher` as a bean. -In Java configuration, this might look like the following: - -==== -[source,java,indent=0] ----- -include::{docs-test-dir}docs/http/RedisHttpSessionConfig.java[tags=config] ----- -==== - -In XML configuration, this might look like the following: - -==== -[source,xml,indent=0] ----- -include::{docs-test-resources-dir}docs/http/HttpSessionListenerXmlTests-context.xml[tags=config] ----- -==== - -[[websocket]] -== WebSocket Integration - -Spring Session provides transparent integration with Spring's WebSocket support. - -include::guides/boot-websocket.adoc[tags=disclaimer,leveloffset=+1] - -[[websocket-why]] -=== Why Spring Session and WebSockets? - -So why do we need Spring Session when we use WebSockets? - -Consider an email application that does much of its work through HTTP requests. -However, there is also a chat application embedded within it that works over WebSocket APIs. -If a user is actively chatting with someone, we should not timeout the `HttpSession`, since this would be a pretty poor user experience. -However, this is exactly what https://java.net/jira/browse/WEBSOCKET_SPEC-175[JSR-356] does. - -Another issue is that, according to JSR-356, if the `HttpSession` times out, any WebSocket that was created with that `HttpSession` and an authenticated user should be forcibly closed. -This means that, if we are actively chatting in our application and are not using the HttpSession, we also do disconnect from our conversation. - -[[websocket-usage]] -=== WebSocket Usage - -The <> provides a working sample of how to integrate Spring Session with WebSockets. -You can follow the basic steps for integration described in the next few headings, but we encourage you to follow along with the detailed WebSocket Guide when integrating with your own application. - -[[websocket-httpsession]] -==== `HttpSession` Integration - -Before using WebSocket integration, you should be sure that you have <> working first. - -include::guides/boot-websocket.adoc[tags=config,leveloffset=+2] - -[[websession]] -== WebSession Integration - -Spring Session provides transparent integration with Spring WebFlux's `WebSession`. -This means that you can switch the `WebSession` implementation out with an implementation that is backed by Spring Session. - -[[websession-why]] -=== Why Spring Session and WebSession? - -We have already mentioned that Spring Session provides transparent integration with Spring WebFlux's `WebSession`, but what benefits do we get out of this? -As with `HttpSession`, Spring Session makes it trivial to support <> without being tied to an application container specific solution. - -[[websession-redis]] -=== WebSession with Redis - -Using Spring Session with `WebSession` is enabled by registering a `WebSessionManager` implementation backed by Spring Session's `ReactiveSessionRepository`. -The Spring configuration is responsible for creating a `WebSessionManager` that replaces the `WebSession` implementation with an implementation backed by Spring Session. -To do so, add the following Spring Configuration: - -==== -[source, java] ----- -@EnableRedisWebSession // <1> -public class SessionConfiguration { - - @Bean - public LettuceConnectionFactory redisConnectionFactory() { - return new LettuceConnectionFactory(); // <2> - } - -} ----- - -<1> The `@EnableRedisWebSession` annotation creates a Spring bean with the name of `webSessionManager`. That bean implements the `WebSessionManager`. -This is what is in charge of replacing the `WebSession` implementation to be backed by Spring Session. -In this instance, Spring Session is backed by Redis. -<2> We create a `RedisConnectionFactory` that connects Spring Session to the Redis Server. -We configure the connection to connect to localhost on the default port (6379) -For more information on configuring Spring Data Redis, see the https://docs.spring.io/spring-data/data-redis/docs/{spring-data-redis-version}/reference/html/[reference documentation]. -==== - -[[websession-how]] -=== How WebSession Integration Works - -It is considerably easier for Spring Session to integrate with Spring WebFlux and its `WebSession`, compared to Servlet API and its `HttpSession`. -Spring WebFlux provides the `WebSessionStore` API, which presents a strategy for persisting `WebSession`. - -NOTE: This section describes how Spring Session provides transparent integration with `WebSession`. We offer this content so that you can understand what is happening under the covers. This functionality is already integrated and you do NOT need to implement this logic yourself. - -First, we create a custom `SpringSessionWebSession` that delegates to Spring Session's `Session`. -It looks something like the following: - -==== -[source, java] ----- -public class SpringSessionWebSession implements WebSession { - - enum State { - NEW, STARTED - } - - private final S session; - - private AtomicReference state = new AtomicReference<>(); - - SpringSessionWebSession(S session, State state) { - this.session = session; - this.state.set(state); - } - - @Override - public void start() { - this.state.compareAndSet(State.NEW, State.STARTED); - } - - @Override - public boolean isStarted() { - State value = this.state.get(); - return (State.STARTED.equals(value) - || (State.NEW.equals(value) && !this.session.getAttributes().isEmpty())); - } - - @Override - public Mono changeSessionId() { - return Mono.defer(() -> { - this.session.changeSessionId(); - return save(); - }); - } - - // ... other methods delegate to the original Session -} ----- -==== - -Next, we create a custom `WebSessionStore` that delegates to the `ReactiveSessionRepository` and wraps `Session` into custom `WebSession` implementation, as the following listing shows: - -==== -[source, java] ----- -public class SpringSessionWebSessionStore implements WebSessionStore { - - private final ReactiveSessionRepository sessions; - - public SpringSessionWebSessionStore(ReactiveSessionRepository reactiveSessionRepository) { - this.sessions = reactiveSessionRepository; - } - - // ... -} ----- -==== - -To be detected by Spring WebFlux, this custom `WebSessionStore` needs to be registered with `ApplicationContext` as a bean named `webSessionManager`. -For additional information on Spring WebFlux, see the https://docs.spring.io/spring-framework/docs/{spring-framework-version}/reference/html/web-reactive.html[Spring Framework Reference Documentation]. - -[[spring-security]] -== Spring Security Integration - -Spring Session provides integration with Spring Security. - -[[spring-security-rememberme]] -=== Spring Security Remember-me Support - -Spring Session provides integration with https://docs.spring.io/spring-security/site/docs/{spring-security-version}/reference/htmlsingle/#remember-me[Spring Security's Remember-me Authentication]. -The support: - -* Changes the session expiration length -* Ensures that the session cookie expires at `Integer.MAX_VALUE`. -The cookie expiration is set to the largest possible value, because the cookie is set only when the session is created. -If it were set to the same value as the session expiration, the session would get renewed when the user used it but the cookie expiration would not be updated (causing the expiration to be fixed). - -To configure Spring Session with Spring Security in Java Configuration, you can use the following listing as a guide: - -==== -[source,java,indent=0] ----- -include::{docs-test-dir}docs/security/RememberMeSecurityConfiguration.java[tags=http-rememberme] - } - -include::{docs-test-dir}docs/security/RememberMeSecurityConfiguration.java[tags=rememberme-bean] ----- -==== - -An XML-based configuration would look something like the following: - -==== -[source,xml,indent=0] ----- -include::{docs-test-resources-dir}docs/security/RememberMeSecurityConfigurationXmlTests-context.xml[tags=config] ----- -==== - -[[spring-security-concurrent-sessions]] -=== Spring Security Concurrent Session Control - - -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 also works in a clustered environment. This is done by providing a custom -implementation of Spring Security's `SessionRegistry` interface. - -When using Spring Security's Java config DSL, you can configure the custom `SessionRegistry` through the -`SessionManagementConfigurer`, as the following listing shows: - -==== -[source,java,indent=0] ----- -include::{docs-test-dir}docs/security/SecurityConfiguration.java[tags=class] ----- -==== - -This assumes that you have also configured Spring Session to provide a `FindByIndexNameSessionRepository` that -returns `Session` instances. - -When using XML configuration, it would look something like the following listing: - -==== -[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. - -[[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 by using Spring Session. This method is never called by Spring Security, -so this affects only applications that access the `SessionRegistry` themselves. - [[api]] -== API Documentation += API Documentation You can browse the complete link:../../api/[Javadoc] online. The key APIs are described in the following sections: @@ -598,12 +18,13 @@ You can browse the complete link:../../api/[Javadoc] online. The key APIs are de * <> [[api-session]] -=== Using `Session` +== Using `Session` A `Session` is a simplified `Map` of name value pairs. Typical usage might look like the following listing: + ==== [source,java,indent=0] ---- @@ -642,15 +63,15 @@ If the `Session` were expired, the result would be null. ==== [[api-sessionrepository]] -=== Using `SessionRepository` +== Using `SessionRepository` A `SessionRepository` is in charge of creating, retrieving, and persisting `Session` instances. If possible, you should not interact directly with a `SessionRepository` or a `Session`. -Instead, developers should prefer interacting with `SessionRepository` and `Session` indirectly through the <> and <> integration. +Instead, developers should prefer interacting with `SessionRepository` and `Session` indirectly through the xref:http-session.adoc#httpsession[`HttpSession`] and xref:web-socket.adoc#websocket[WebSocket] integration. [[api-findbyindexnamesessionrepository]] -=== Using `FindByIndexNameSessionRepository` +== Using `FindByIndexNameSessionRepository` Spring Session's most basic API for using a `Session` is the `SessionRepository`. This API is intentionally very simple, so that you can easily provide additional implementations with basic functionality. @@ -684,15 +105,15 @@ include::{docs-test-dir}docs/FindByIndexNameSessionRepositoryTests.java[tags=fin ==== [[api-reactivesessionrepository]] -=== Using `ReactiveSessionRepository` +== Using `ReactiveSessionRepository` A `ReactiveSessionRepository` is in charge of creating, retrieving, and persisting `Session` instances in a non-blocking and reactive manner. If possible, you should not interact directly with a `ReactiveSessionRepository` or a `Session`. -Instead, you should prefer interacting with `ReactiveSessionRepository` and `Session` indirectly through the <> integration. +Instead, you should prefer interacting with `ReactiveSessionRepository` and `Session` indirectly through the xref:web-session.adoc#websession[WebSession] integration. [[api-enablespringhttpsession]] -=== Using `@EnableSpringHttpSession` +== Using `@EnableSpringHttpSession` You can add the `@EnableSpringHttpSession` annotation to a `@Configuration` class to expose the `SessionRepositoryFilter` as a bean named `springSessionRepositoryFilter`. In order to use the annotation, you must provide a single `SessionRepository` bean. @@ -710,7 +131,7 @@ This is because things such as session expiration are highly implementation-depe This means that, if you need to clean up expired sessions, you are responsible for cleaning up the expired sessions. [[api-enablespringwebsession]] -=== Using `@EnableSpringWebSession` +== Using `@EnableSpringWebSession` You can add the `@EnableSpringWebSession` annotation to a `@Configuration` class to expose the `WebSessionManager` as a bean named `webSessionManager`. To use the annotation, you must provide a single `ReactiveSessionRepository` bean. @@ -728,14 +149,14 @@ This is because things such as session expiration are highly implementation-depe This means that, if you require cleaning up expired sessions, you are responsible for cleaning up the expired sessions. [[api-redisindexedsessionrepository]] -=== Using `RedisIndexedSessionRepository` +== Using `RedisIndexedSessionRepository` `RedisIndexedSessionRepository` is a `SessionRepository` that is implemented by using Spring Data's `RedisOperations`. In a web environment, this is typically used in combination with `SessionRepositoryFilter`. The implementation supports `SessionDestroyedEvent` and `SessionCreatedEvent` through `SessionMessageListener`. [[api-redisindexedsessionrepository-new]] -==== Instantiating a `RedisIndexedSessionRepository` +=== Instantiating a `RedisIndexedSessionRepository` You can see a typical example of how to create a new instance in the following listing: @@ -749,10 +170,10 @@ include::{indexdoc-tests}[tags=new-redisindexedsessionrepository] For additional information on how to create a `RedisConnectionFactory`, see the Spring Data Redis Reference. [[api-redisindexedsessionrepository-config]] -==== Using `@EnableRedisHttpSession` +=== Using `@EnableRedisHttpSession` In a web environment, the simplest way to create a new `RedisIndexedSessionRepository` is to use `@EnableRedisHttpSession`. -You can find complete example usage in the <>. +You can find complete example usage in the xref:samples.adoc#samples[Samples and Guides (Start Here)]. You can use the following attributes to customize the configuration: * *maxInactiveIntervalInSeconds*: The amount of time before the session expires, in seconds. @@ -760,18 +181,18 @@ You can use the following attributes to customize the configuration: * *flushMode*: Allows specifying when data is written to Redis. The default is only when `save` is invoked on `SessionRepository`. A value of `FlushMode.IMMEDIATE` writes to Redis as soon as possible. -===== Custom `RedisSerializer` +==== Custom `RedisSerializer` You can customize the serialization by creating a bean named `springSessionDefaultRedisSerializer` that implements `RedisSerializer`. -==== Redis `TaskExecutor` +=== Redis `TaskExecutor` `RedisIndexedSessionRepository` is subscribed to receive events from Redis by using a `RedisMessageListenerContainer`. You can customize the way those events are dispatched by creating a bean named `springSessionRedisTaskExecutor`, a bean `springSessionRedisSubscriptionExecutor`, or both. You can find more details on configuring Redis task executors https://docs.spring.io/spring-data-redis/docs/{spring-data-redis-version}/reference/html/#redis:pubsub:subscribe:containers[here]. [[api-redisindexedsessionrepository-storage]] -==== Storage Details +=== Storage Details The following sections outline how Redis is updated for each operation. The following example shows an example of creating a new session: @@ -793,7 +214,7 @@ EXPIRE spring:session:expirations1439245080000 2100 The subsequent sections describe the details. -===== Saving a Session +==== Saving a Session Each session is stored in Redis as a `Hash`. Each session is set and updated by using the `HMSET` command. @@ -820,7 +241,7 @@ The first is `attrName`, with a value of `someAttrValue`. The second session attribute is named `attrName2`, with a value of `someAttrValue2`. [[api-redisindexedsessionrepository-writes]] -===== Optimized Writes +==== Optimized Writes The `Session` instances managed by `RedisIndexedSessionRepository` keeps track of the properties that have changed and updates only those. This means that, if an attribute is written once and read many times, we need to write that attribute only once. @@ -834,7 +255,7 @@ HMSET spring:session:sessions:33fdd1b6-b496-4b33-9f7d-df96679d32fe sessionAttr:a ==== [[api-redisindexedsessionrepository-expiration]] -===== Session Expiration +==== Session Expiration An expiration is associated with each session by using the `EXPIRE` command, based upon the `Session.getMaxInactiveInterval()`. The following example shows a typical `EXPIRE` command: @@ -894,7 +315,7 @@ By simply accessing the key, we ensure that the key is only removed if the TTL o [[api-redisindexedsessionrepository-sessiondestroyedevent]] -==== `SessionDeletedEvent` and `SessionExpiredEvent` +=== `SessionDeletedEvent` and `SessionExpiredEvent` `SessionDeletedEvent` and `SessionExpiredEvent` are both types of `SessionDestroyedEvent`. @@ -938,7 +359,7 @@ include::{docs-test-resources-dir}docs/HttpSessionConfigurationNoOpConfigureRedi ==== [[api-redisindexedsessionrepository-sessioncreatedevent]] -==== Using `SessionCreatedEvent` +=== Using `SessionCreatedEvent` When a session is created, an event is sent to Redis with a channel ID of `spring:session:channel:created:33fdd1b6-b496-4b33-9f7d-df96679d32fe`, where `33fdd1b6-b496-4b33-9f7d-df96679d32fe` is the session ID. The body of the event is the session that was created. @@ -946,7 +367,7 @@ where `33fdd1b6-b496-4b33-9f7d-df96679d32fe` is the session ID. The body of the If registered as a `MessageListener` (the default), `RedisIndexedSessionRepository` then translates the Redis message into a `SessionCreatedEvent`. [[api-redisindexedsessionrepository-cli]] -==== Viewing the Session in Redis +=== Viewing the Session in Redis After https://redis.io/topics/quickstart[installing redis-cli], you can inspect the values in Redis https://redis.io/commands#hash[using the redis-cli]. For example, you can enter the following into a terminal: @@ -981,13 +402,13 @@ redis 127.0.0.1:6379> hget spring:session:sessions:4fc39ce3-63b3-4e17-b1c4-5e1ed ==== [[api-reactiveredissessionrepository]] -=== Using `ReactiveRedisSessionRepository` +== Using `ReactiveRedisSessionRepository` `ReactiveRedisSessionRepository` is a `ReactiveSessionRepository` that is implemented by using Spring Data's `ReactiveRedisOperations`. In a web environment, this is typically used in combination with `WebSessionStore`. [[api-reactiveredissessionrepository-new]] -==== Instantiating a `ReactiveRedisSessionRepository` +=== Instantiating a `ReactiveRedisSessionRepository` The following example shows how to create a new instance: @@ -1001,7 +422,7 @@ include::{indexdoc-tests}[tags=new-reactiveredissessionrepository] For additional information on how to create a `ReactiveRedisConnectionFactory`, see the Spring Data Redis Reference. [[api-reactiveredissessionrepository-config]] -==== Using `@EnableRedisWebSession` +=== Using `@EnableRedisWebSession` In a web environment, the simplest way to create a new `ReactiveRedisSessionRepository` is to use `@EnableRedisWebSession`. You can use the following attributes to customize the configuration: @@ -1012,13 +433,13 @@ You can use the following attributes to customize the configuration: A value of `FlushMode.IMMEDIATE` writes to Redis as soon as possible. [[api-reactiveredissessionrepository-writes]] -===== Optimized Writes +==== Optimized Writes The `Session` instances managed by `ReactiveRedisSessionRepository` keep track of the properties that have changed and updates only those. This means that, if an attribute is written once and read many times, we need to write that attribute only once. [[api-reactiveredissessionrepository-cli]] -==== Viewing the Session in Redis +=== Viewing the Session in Redis After https://redis.io/topics/quickstart[installing redis-cli], you can inspect the values in Redis https://redis.io/commands#hash[using the redis-cli]. For example, you can enter the following command into a terminal window: @@ -1051,14 +472,14 @@ redis 127.0.0.1:6379> hget spring:session:sessions:4fc39ce3-63b3-4e17-b1c4-5e1ed ==== [[api-mapsessionrepository]] -=== Using `MapSessionRepository` +== Using `MapSessionRepository` The `MapSessionRepository` allows for persisting `Session` in a `Map`, with the key being the `Session` ID and the value being the `Session`. You can use the implementation with a `ConcurrentHashMap` as a testing or convenience mechanism. Alternatively, you can use it with distributed `Map` implementations. For example, it can be used with Hazelcast. [[api-mapsessionrepository-new]] -==== Instantiating `MapSessionRepository` +=== Instantiating `MapSessionRepository` The following example shows how to create a new instance: @@ -1070,9 +491,9 @@ include::{indexdoc-tests}[tags=new-mapsessionrepository] ==== [[api-mapsessionrepository-hazelcast]] -==== Using Spring Session and Hazlecast +=== Using Spring Session and Hazlecast -The <> is a complete application that demonstrates how to use Spring Session with Hazelcast. +The xref:samples.adoc#samples[Hazelcast Sample] is a complete application that demonstrates how to use Spring Session with Hazelcast. To run it, use the following command: @@ -1082,7 +503,7 @@ To run it, use the following command: ---- ==== -The <> is a complete application that demonstrates how to use Spring Session with Hazelcast and Spring Security. +The xref:samples.adoc#samples[Hazelcast Spring Sample] is a complete application that demonstrates how to use Spring Session with Hazelcast and Spring Security. It includes example Hazelcast `MapListener` implementations that support firing `SessionCreatedEvent`, `SessionDeletedEvent`, and `SessionExpiredEvent`. @@ -1095,21 +516,21 @@ To run it, use the following command: ==== [[api-reactivemapsessionrepository]] -=== Using `ReactiveMapSessionRepository` +== Using `ReactiveMapSessionRepository` The `ReactiveMapSessionRepository` allows for persisting `Session` in a `Map`, with the key being the `Session` ID and the value being the `Session`. You can use the implementation with a `ConcurrentHashMap` as a testing or convenience mechanism. Alternatively, you can use it with distributed `Map` implementations, with the requirement that the supplied `Map` must be non-blocking. [[api-jdbcindexedsessionrepository]] -=== Using `JdbcIndexedSessionRepository` +== Using `JdbcIndexedSessionRepository` `JdbcIndexedSessionRepository` is a `SessionRepository` implementation that uses Spring's `JdbcOperations` to store sessions in a relational database. In a web environment, this is typically used in combination with `SessionRepositoryFilter`. Note that this implementation does not support publishing of session events. [[api-jdbcindexedsessionrepository-new]] -==== Instantiating a `JdbcIndexedSessionRepository` +=== Instantiating a `JdbcIndexedSessionRepository` The following example shows how to create a new instance: @@ -1123,27 +544,27 @@ include::{indexdoc-tests}[tags=new-jdbcindexedsessionrepository] For additional information on how to create and configure `JdbcTemplate` and `PlatformTransactionManager`, see the https://docs.spring.io/spring/docs/{spring-framework-version}/spring-framework-reference/data-access.html[Spring Framework Reference Documentation]. [[api-jdbcindexedsessionrepository-config]] -==== Using `@EnableJdbcHttpSession` +=== Using `@EnableJdbcHttpSession` In a web environment, the simplest way to create a new `JdbcIndexedSessionRepository` is to use `@EnableJdbcHttpSession`. -You can find complete example usage in the <> +You can find complete example usage in the xref:samples.adoc#samples[Samples and Guides (Start Here)] You can use the following attributes to customize the configuration: * *tableName*: The name of database table used by Spring Session to store sessions * *maxInactiveIntervalInSeconds*: The amount of time before the session will expire in seconds -===== Customizing `LobHandler` +==== Customizing `LobHandler` You can customize BLOB handling by creating a bean named `springSessionLobHandler` that implements `LobHandler`. -===== Customizing `ConversionService` +==== Customizing `ConversionService` You can customize the default serialization and deserialization of the session by providing a `ConversionService` instance. When working in a typical Spring environment, the default `ConversionService` bean (named `conversionService`) is automatically picked up and used for serialization and deserialization. However, you can override the default `ConversionService` by providing a bean named `springSessionConversionService`. [[api-jdbcindexedsessionrepository-storage]] -==== Storage Details +=== Storage Details By default, this implementation uses `SPRING_SESSION` and `SPRING_SESSION_ATTRIBUTES` tables to store sessions. Note that you can customize the table name, as already described. In that case, the table used to store attributes is named by using the provided table name suffixed with `_ATTRIBUTES`. @@ -1170,19 +591,19 @@ include::{session-jdbc-main-resources-dir}org/springframework/session/jdbc/schem ---- ==== -==== Transaction Management +=== Transaction Management All JDBC operations in `JdbcIndexedSessionRepository` are performed in a transactional manner. Transactions are performed with propagation set to `REQUIRES_NEW` in order to avoid unexpected behavior due to interference with existing transactions (for example, running a `save` operation in a thread that already participates in a read-only transaction). [[api-hazelcastindexedsessionrepository]] -=== Using `HazelcastIndexedSessionRepository` +== Using `HazelcastIndexedSessionRepository` `HazelcastIndexedSessionRepository` is a `SessionRepository` implementation that stores sessions in Hazelcast's distributed `IMap`. In a web environment, this is typically used in combination with `SessionRepositoryFilter`. [[api-hazelcastindexedsessionrepository-new]] -==== Instantiating a `HazelcastIndexedSessionRepository` +=== Instantiating a `HazelcastIndexedSessionRepository` The following example shows how to create a new instance: @@ -1196,31 +617,31 @@ include::{indexdoc-tests}[tags=new-hazelcastindexedsessionrepository] For additional information on how to create and configure Hazelcast instance, see the https://docs.hazelcast.org/docs/{hazelcast-version}/manual/html-single/index.html#hazelcast-configuration[Hazelcast documentation]. [[api-enablehazelcasthttpsession]] -==== Using `@EnableHazelcastHttpSession` +=== Using `@EnableHazelcastHttpSession` To use https://hazelcast.org/[Hazelcast] as your backing source for the `SessionRepository`, you can add the `@EnableHazelcastHttpSession` annotation to a `@Configuration` class. Doing so extends the functionality provided by the `@EnableSpringHttpSession` annotation but makes the `SessionRepository` for you in Hazelcast. You must provide a single `HazelcastInstance` bean for the configuration to work. -You can find a complete configuration example in the <>. +You can find a complete configuration example in the xref:samples.adoc#samples[Samples and Guides (Start Here)]. [[api-enablehazelcasthttpsession-customize]] -==== Basic Customization +=== Basic Customization You can use the following attributes on `@EnableHazelcastHttpSession` to customize the configuration: * *maxInactiveIntervalInSeconds*: The amount of time before the session expires, in seconds. The default is 1800 seconds (30 minutes) * *sessionMapName*: The name of the distributed `Map` that is used in Hazelcast to store the session data. [[api-enablehazelcasthttpsession-events]] -==== Session Events +=== Session Events Using a `MapListener` to respond to entries being added, evicted, and removed from the distributed `Map` causes these events to trigger publishing of `SessionCreatedEvent`, `SessionExpiredEvent`, and `SessionDeletedEvent` events (respectively) through the `ApplicationEventPublisher`. [[api-enablehazelcasthttpsession-storage]] -==== Storage Details +=== Storage Details Sessions are stored in a distributed `IMap` in Hazelcast. The `IMap` interface methods are used to `get()` and `put()` Sessions. -Additionally, the `values()` method supports a `FindByIndexNameSessionRepository#findByIndexNameAndIndexValue` operation, together with appropriate `ValueExtractor` (which needs to be registered with Hazelcast). See the <> for more details on this configuration. +Additionally, the `values()` method supports a `FindByIndexNameSessionRepository#findByIndexNameAndIndexValue` operation, together with appropriate `ValueExtractor` (which needs to be registered with Hazelcast). See the xref:samples.adoc#samples[ Hazelcast Spring Sample] for more details on this configuration. The expiration of a session in the `IMap` is handled by Hazelcast's support for setting the time to live on an entry when it is `put()` into the `IMap`. Entries (sessions) that have been idle longer than the time to live are automatically removed from the `IMap`. You should not need to configure any settings such as `max-idle-seconds` or `time-to-live-seconds` for the `IMap` within the Hazelcast configuration. @@ -1231,13 +652,13 @@ Note that if you use Hazelcast's `MapStore` to persist your sessions `IMap`, the * Reloading uses default TTL for a given `IMap` results in sessions losing their original TTL [[api-cookieserializer]] -=== Using `CookieSerializer` +== Using `CookieSerializer` A `CookieSerializer` is responsible for defining how the session cookie is written. Spring Session comes with a default implementation using `DefaultCookieSerializer`. [[api-cookieserializer-bean]] -==== Exposing `CookieSerializer` as a bean +=== Exposing `CookieSerializer` as a bean Exposing the `CookieSerializer` as a Spring bean augments the existing configuration when you use configurations like `@EnableRedisHttpSession`. The following example shows how to do so: @@ -1262,7 +683,7 @@ WARNING: You should only match on valid domain characters, since the domain name Doing so prevents a malicious user from performing such attacks as https://en.wikipedia.org/wiki/HTTP_response_splitting[HTTP Response Splitting]. [[api-cookieserializer-customization]] -==== Customizing `CookieSerializer` +=== Customizing `CookieSerializer` You can customize how the session cookie is written by using any of the following configuration options on the `DefaultCookieSerializer`. @@ -1307,111 +728,3 @@ All of the `SessionRepository` implementations provided by Spring Session use th Note that the same recommendations apply for implementing a custom <> as well. In this case, you should use the <>. - -[[upgrading-2.0]] -== Upgrading to 2.x - -With the new major release version, the Spring Session team took the opportunity to make some non-passive changes. -The focus of these changes is to improve and harmonize Spring Session's APIs as well as remove the deprecated components. - -=== Baseline Update - -Spring Session 2.0 requires Java 8 and Spring Framework 5.0 as a baseline, since its entire codebase is now based on Java 8 source code. -See https://github.com/spring-projects/spring-framework/wiki/Upgrading-to-Spring-Framework-5.x[Upgrading to Spring Framework 5.x] for more on upgrading Spring Framework. - -=== Replaced and Removed Modules - -As a part of the project's splitting of the modules, the existing `spring-session` has been replaced with the `spring-session-core` module. -The `spring-session-core` module holds only the common set of APIs and components, while other modules contain the implementation of the appropriate `SessionRepository` and functionality related to that data store. -This applies to several existing modules that were previously a simple dependency aggregator helper module. -With new module arrangement, the following modules actually carry the implementation: - -* Spring Session Data Redis -* Spring Session JDBC -* Spring Session Hazelcast - -Also, the following modules were removed from the main project repository: - -* Spring Session Data MongoDB -* Spring Session Data GemFire - -Note that these two have moved to separate repositories and continue to be available under new artifact names: - -* https://github.com/spring-projects/spring-session-data-mongodb[`spring-session-data-mongodb`] -* https://github.com/spring-projects/spring-session-data-geode[`spring-session-data-geode`] - -=== Replaced and Removed Packages, Classes, and Methods - -The following changes were made to packages, classes, and methods: - -* `ExpiringSession` API has been merged into the `Session` API. -* The `Session` API has been enhanced to make full use of Java 8. -* The `Session` API has been extended with `changeSessionId` support. -* The `SessionRepository` API has been updated to better align with Spring Data method naming conventions. -* `AbstractSessionEvent` and its subclasses are no longer constructable without an underlying `Session` object. -* The Redis namespace used by `RedisOperationsSessionRepository` is now fully configurable, instead of being partially configurable. -* Redis configuration support has been updated to avoid registering a Spring Session-specific `RedisTemplate` bean. -* JDBC configuration support has been updated to avoid registering a Spring Session-specific `JdbcTemplate` bean. -* Previously deprecated classes and methods have been removed across the codebase - -=== Dropped Support - -As a part of the changes to `HttpSessionStrategy` and its alignment to the counterpart from the reactive world, the support for managing multiple users' sessions in a single browser instance has been removed. -The introduction of a new API to replace this functionality is under consideration for future releases. - -[[community]] -== Spring Session Community - -We are glad to consider you a part of our community. -The following sections provide additional about how to interact with the Spring Session community. - -[[community-support]] -=== Support - -You can get help by asking questions on https://stackoverflow.com/questions/tagged/spring-session[Stack Overflow with the `spring-session` tag]. -Similarly, we encourage helping others by answering questions on Stack Overflow. - -[[community-source]] -=== Source Code - -You can find the source code on GitHub at https://github.com/spring-projects/spring-session/ - -[[community-issues]] -=== Issue Tracking - -We track issues in GitHub issues at https://github.com/spring-projects/spring-session/issues - -[[community-contributing]] -=== Contributing - -We appreciate https://help.github.com/articles/using-pull-requests/[pull requests]. - -[[community-license]] -=== License - -Spring Session is Open Source software released under the https://www.apache.org/licenses/LICENSE-2.0[Apache 2.0 license]. - -[[community-extensions]] -=== Community Extensions - -|=== -| Name | Location - -| Spring Session Infinispan -| https://infinispan.org/infinispan-spring-boot/master/spring_boot_starter.html#_enabling_spring_session_support - -|=== - -[[minimum-requirements]] -== Minimum Requirements - -The minimum requirements for Spring Session are: - -* Java 8+. -* If you run in a Servlet Container (not required), Servlet 3.1+. -* If you use other Spring libraries (not required), the minimum required version is Spring 5.0.x. -* `@EnableRedisHttpSession` requires Redis 2.8+. This is necessary to support <> -* `@EnableHazelcastHttpSession` requires Hazelcast 3.6+. This is necessary to support <> - -NOTE: At its core, Spring Session has a required dependency only on `spring-jcl`. -For an example of using Spring Session without any other Spring dependencies, see the <> application. diff --git a/spring-session-docs/src/docs/asciidoc/guides/boot-findbyusername.adoc b/spring-session-docs/modules/ROOT/pages/guides/boot-findbyusername.adoc similarity index 99% rename from spring-session-docs/src/docs/asciidoc/guides/boot-findbyusername.adoc rename to spring-session-docs/modules/ROOT/pages/guides/boot-findbyusername.adoc index 1b201e22..21c344d5 100644 --- a/spring-session-docs/src/docs/asciidoc/guides/boot-findbyusername.adoc +++ b/spring-session-docs/modules/ROOT/pages/guides/boot-findbyusername.adoc @@ -1,6 +1,5 @@ = Spring Session - find by username Rob Winch -:toc: left :stylesdir: ../ :highlightjsdir: ../js/highlight :docinfodir: guides diff --git a/spring-session-docs/src/docs/asciidoc/guides/boot-jdbc.adoc b/spring-session-docs/modules/ROOT/pages/guides/boot-jdbc.adoc similarity index 99% rename from spring-session-docs/src/docs/asciidoc/guides/boot-jdbc.adoc rename to spring-session-docs/modules/ROOT/pages/guides/boot-jdbc.adoc index 8884d0ec..c3cb4129 100644 --- a/spring-session-docs/src/docs/asciidoc/guides/boot-jdbc.adoc +++ b/spring-session-docs/modules/ROOT/pages/guides/boot-jdbc.adoc @@ -1,6 +1,5 @@ = Spring Session - Spring Boot Rob Winch, Vedran Pavić -:toc: left :stylesdir: ../ :highlightjsdir: ../js/highlight :docinfodir: guides diff --git a/spring-session-docs/src/docs/asciidoc/guides/boot-redis.adoc b/spring-session-docs/modules/ROOT/pages/guides/boot-redis.adoc similarity index 99% rename from spring-session-docs/src/docs/asciidoc/guides/boot-redis.adoc rename to spring-session-docs/modules/ROOT/pages/guides/boot-redis.adoc index 60617e92..dc2f23be 100644 --- a/spring-session-docs/src/docs/asciidoc/guides/boot-redis.adoc +++ b/spring-session-docs/modules/ROOT/pages/guides/boot-redis.adoc @@ -1,6 +1,5 @@ = Spring Session - Spring Boot Rob Winch, Vedran Pavić -:toc: left :stylesdir: ../ :highlightjsdir: ../js/highlight :docinfodir: guides diff --git a/spring-session-docs/src/docs/asciidoc/guides/boot-webflux-custom-cookie.adoc b/spring-session-docs/modules/ROOT/pages/guides/boot-webflux-custom-cookie.adoc similarity index 99% rename from spring-session-docs/src/docs/asciidoc/guides/boot-webflux-custom-cookie.adoc rename to spring-session-docs/modules/ROOT/pages/guides/boot-webflux-custom-cookie.adoc index e48b3fbe..a4a2bdaf 100644 --- a/spring-session-docs/src/docs/asciidoc/guides/boot-webflux-custom-cookie.adoc +++ b/spring-session-docs/modules/ROOT/pages/guides/boot-webflux-custom-cookie.adoc @@ -1,6 +1,5 @@ = Spring Session - WebFlux with Custom Cookie Eleftheria Stein-Kousathana -:toc: left :stylesdir: ../ :highlightjsdir: ../js/highlight :docinfodir: guides diff --git a/spring-session-docs/src/docs/asciidoc/guides/boot-websocket.adoc b/spring-session-docs/modules/ROOT/pages/guides/boot-websocket.adoc similarity index 99% rename from spring-session-docs/src/docs/asciidoc/guides/boot-websocket.adoc rename to spring-session-docs/modules/ROOT/pages/guides/boot-websocket.adoc index e4659eab..8c0b45e9 100644 --- a/spring-session-docs/src/docs/asciidoc/guides/boot-websocket.adoc +++ b/spring-session-docs/modules/ROOT/pages/guides/boot-websocket.adoc @@ -1,6 +1,5 @@ = Spring Session - WebSocket Rob Winch -:toc: left :websocketdoc-test-dir: {docs-test-dir}docs/websocket/ :stylesdir: ../ :highlightjsdir: ../js/highlight diff --git a/spring-session-docs/src/docs/asciidoc/guides/docinfo-footer.html b/spring-session-docs/modules/ROOT/pages/guides/docinfo-footer.html similarity index 100% rename from spring-session-docs/src/docs/asciidoc/guides/docinfo-footer.html rename to spring-session-docs/modules/ROOT/pages/guides/docinfo-footer.html diff --git a/spring-session-docs/src/docs/asciidoc/guides/java-custom-cookie.adoc b/spring-session-docs/modules/ROOT/pages/guides/java-custom-cookie.adoc similarity index 99% rename from spring-session-docs/src/docs/asciidoc/guides/java-custom-cookie.adoc rename to spring-session-docs/modules/ROOT/pages/guides/java-custom-cookie.adoc index cddd46b8..142c7a50 100644 --- a/spring-session-docs/src/docs/asciidoc/guides/java-custom-cookie.adoc +++ b/spring-session-docs/modules/ROOT/pages/guides/java-custom-cookie.adoc @@ -1,6 +1,5 @@ = Spring Session - Custom Cookie Rob Winch; Eleftheria Stein-Kousathana -:toc: left :stylesdir: ../ :highlightjsdir: ../js/highlight :docinfodir: guides diff --git a/spring-session-docs/src/docs/asciidoc/guides/java-hazelcast.adoc b/spring-session-docs/modules/ROOT/pages/guides/java-hazelcast.adoc similarity index 98% rename from spring-session-docs/src/docs/asciidoc/guides/java-hazelcast.adoc rename to spring-session-docs/modules/ROOT/pages/guides/java-hazelcast.adoc index b0fd7d20..d301dc9b 100644 --- a/spring-session-docs/src/docs/asciidoc/guides/java-hazelcast.adoc +++ b/spring-session-docs/modules/ROOT/pages/guides/java-hazelcast.adoc @@ -1,6 +1,5 @@ = Spring Session and Spring Security with Hazelcast Tommy Ludwig; Rob Winch -:toc: left :stylesdir: ../ :highlightjsdir: ../js/highlight :docinfodir: guides @@ -111,7 +110,7 @@ with the same `SerializerConfiguration` of members. == Servlet Container Initialization -Our <> created a Spring bean named `springSessionRepositoryFilter` that implements `Filter`. +Our xref:guides/java-security.adoc#security-spring-configuration[Spring Configuration] created a Spring bean named `springSessionRepositoryFilter` that implements `Filter`. The `springSessionRepositoryFilter` bean is responsible for replacing the `HttpSession` with a custom implementation that is backed by Spring Session. In order for our `Filter` to do its magic, Spring needs to load our `SessionConfig` class. diff --git a/spring-session-docs/src/docs/asciidoc/guides/java-jdbc.adoc b/spring-session-docs/modules/ROOT/pages/guides/java-jdbc.adoc similarity index 99% rename from spring-session-docs/src/docs/asciidoc/guides/java-jdbc.adoc rename to spring-session-docs/modules/ROOT/pages/guides/java-jdbc.adoc index 81c49bdf..c725de8f 100644 --- a/spring-session-docs/src/docs/asciidoc/guides/java-jdbc.adoc +++ b/spring-session-docs/modules/ROOT/pages/guides/java-jdbc.adoc @@ -1,6 +1,5 @@ = Spring Session - HttpSession (Quick Start) Rob Winch, Vedran Pavić -:toc: left :stylesdir: ../ :highlightjsdir: ../js/highlight :docinfodir: guides diff --git a/spring-session-docs/src/docs/asciidoc/guides/java-redis.adoc b/spring-session-docs/modules/ROOT/pages/guides/java-redis.adoc similarity index 99% rename from spring-session-docs/src/docs/asciidoc/guides/java-redis.adoc rename to spring-session-docs/modules/ROOT/pages/guides/java-redis.adoc index 7777e194..afaebdec 100644 --- a/spring-session-docs/src/docs/asciidoc/guides/java-redis.adoc +++ b/spring-session-docs/modules/ROOT/pages/guides/java-redis.adoc @@ -1,6 +1,5 @@ = Spring Session - HttpSession (Quick Start) Rob Winch -:toc: left :version-snapshot: true :stylesdir: ../ :highlightjsdir: ../js/highlight diff --git a/spring-session-docs/src/docs/asciidoc/guides/java-rest.adoc b/spring-session-docs/modules/ROOT/pages/guides/java-rest.adoc similarity index 99% rename from spring-session-docs/src/docs/asciidoc/guides/java-rest.adoc rename to spring-session-docs/modules/ROOT/pages/guides/java-rest.adoc index dfcd430e..d8dcb6da 100644 --- a/spring-session-docs/src/docs/asciidoc/guides/java-rest.adoc +++ b/spring-session-docs/modules/ROOT/pages/guides/java-rest.adoc @@ -1,6 +1,5 @@ = Spring Session - REST Rob Winch -:toc: left :stylesdir: ../ :highlightjsdir: ../js/highlight :docinfodir: guides diff --git a/spring-session-docs/src/docs/asciidoc/guides/java-security.adoc b/spring-session-docs/modules/ROOT/pages/guides/java-security.adoc similarity index 99% rename from spring-session-docs/src/docs/asciidoc/guides/java-security.adoc rename to spring-session-docs/modules/ROOT/pages/guides/java-security.adoc index 65c5f5cc..f183c2b4 100644 --- a/spring-session-docs/src/docs/asciidoc/guides/java-security.adoc +++ b/spring-session-docs/modules/ROOT/pages/guides/java-security.adoc @@ -1,6 +1,5 @@ = Spring Session and Spring Security Rob Winch -:toc: left :stylesdir: ../ :highlightjsdir: ../js/highlight :docinfodir: guides diff --git a/spring-session-docs/src/docs/asciidoc/guides/xml-jdbc.adoc b/spring-session-docs/modules/ROOT/pages/guides/xml-jdbc.adoc similarity index 99% rename from spring-session-docs/src/docs/asciidoc/guides/xml-jdbc.adoc rename to spring-session-docs/modules/ROOT/pages/guides/xml-jdbc.adoc index 455a37fc..ec084e25 100644 --- a/spring-session-docs/src/docs/asciidoc/guides/xml-jdbc.adoc +++ b/spring-session-docs/modules/ROOT/pages/guides/xml-jdbc.adoc @@ -1,6 +1,5 @@ = Spring Session - HttpSession (Quick Start) Rob Winch, Vedran Pavić -:toc: left :stylesdir: ../ :highlightjsdir: ../js/highlight :docinfodir: guides diff --git a/spring-session-docs/src/docs/asciidoc/guides/xml-redis.adoc b/spring-session-docs/modules/ROOT/pages/guides/xml-redis.adoc similarity index 99% rename from spring-session-docs/src/docs/asciidoc/guides/xml-redis.adoc rename to spring-session-docs/modules/ROOT/pages/guides/xml-redis.adoc index 4a5a2db5..70592453 100644 --- a/spring-session-docs/src/docs/asciidoc/guides/xml-redis.adoc +++ b/spring-session-docs/modules/ROOT/pages/guides/xml-redis.adoc @@ -1,6 +1,5 @@ = Spring Session - HttpSession (Quick Start) Rob Winch -:toc: left :stylesdir: ../ :highlightjsdir: ../js/highlight :docinfodir: guides diff --git a/spring-session-docs/modules/ROOT/pages/http-session.adoc b/spring-session-docs/modules/ROOT/pages/http-session.adoc new file mode 100644 index 00000000..98700711 --- /dev/null +++ b/spring-session-docs/modules/ROOT/pages/http-session.adoc @@ -0,0 +1,194 @@ +[[httpsession]] += `HttpSession` Integration + +Spring Session provides transparent integration with `HttpSession`. +This means that developers can switch the `HttpSession` implementation out with an implementation that is backed by Spring Session. + +[[httpsession-why]] +== Why Spring Session and `HttpSession`? + +We have already mentioned that Spring Session provides transparent integration with `HttpSession`, but what benefits do we get out of this? + +* *Clustered Sessions*: Spring Session makes it trivial to support <> without being tied to an application container specific solution. +* *RESTful APIs*: Spring Session lets providing session IDs in headers work with <> + +[[httpsession-redis]] +== `HttpSession` with Redis + +Using Spring Session with `HttpSession` is enabled by adding a Servlet Filter before anything that uses the `HttpSession`. +You can choose from enabling this by using either: + +* <> +* <> + +[[httpsession-redis-jc]] +=== Redis Java-based Configuration + +This section describes how to use Redis to back `HttpSession` by using Java based configuration. + +NOTE: The xref:samples.adoc#samples[ HttpSession Sample] provides a working sample of how to integrate Spring Session and `HttpSession` by using Java configuration. +You can read the basic steps for integration in the next few sections, but we encourage you to follow along with the detailed HttpSession Guide when integrating with your own application. + +include::guides/java-redis.adoc[tags=config,leveloffset=+2] + +[[httpsession-redis-xml]] +=== Redis XML-based Configuration + +This section describes how to use Redis to back `HttpSession` by using XML based configuration. + +NOTE: The xref:samples.adoc#samples[ HttpSession XML Sample] provides a working sample of how to integrate Spring Session and `HttpSession` using XML configuration. +You can read the basic steps for integration in the next few sections, but we encourage you to follow along with the detailed HttpSession XML Guide when integrating with your own application. + +include::guides/xml-redis.adoc[tags=config,leveloffset=+2] + +[[httpsession-jdbc]] +== `HttpSession` with JDBC + +You can use Spring Session with `HttpSession` by adding a servlet filter before anything that uses the `HttpSession`. +You can choose to do in any of the following ways: + +* <> +* <> +* <> + +[[httpsession-jdbc-jc]] +=== JDBC Java-based Configuration + +This section describes how to use a relational database to back `HttpSession` when you use Java-based configuration. + +NOTE: The xref:samples.adoc#samples[ HttpSession JDBC Sample] provides a working sample of how to integrate Spring Session and `HttpSession` by using Java configuration. +You can read the basic steps for integration in the next few sections, but we encouraged you to follow along with the detailed HttpSession JDBC Guide when integrating with your own application. + +include::guides/java-jdbc.adoc[tags=config,leveloffset=+2] + +[[httpsession-jdbc-xml]] +=== JDBC XML-based Configuration + +This section describes how to use a relational database to back `HttpSession` when you use XML based configuration. + +NOTE: The xref:samples.adoc#samples[ HttpSession JDBC XML Sample] provides a working sample of how to integrate Spring Session and `HttpSession` by using XML configuration. +You can read the basic steps for integration in the next few sections, but we encourage you to follow along with the detailed HttpSession JDBC XML Guide when integrating with your own application. + +include::guides/xml-jdbc.adoc[tags=config,leveloffset=+2] + +[[httpsession-jdbc-boot]] +=== JDBC Spring Boot-based Configuration + +This section describes how to use a relational database to back `HttpSession` when you use Spring Boot. + +NOTE: The xref:samples.adoc#samples[ HttpSession JDBC Spring Boot Sample] provides a working sample of how to integrate Spring Session and `HttpSession` by using Spring Boot. +You can read the basic steps for integration in the next few sections, but we encourage you to follow along with the detailed HttpSession JDBC Spring Boot Guide when integrating with your own application. + +include::guides/boot-jdbc.adoc[tags=config,leveloffset=+2] + +[[httpsession-hazelcast]] +== HttpSession with Hazelcast + +Using Spring Session with `HttpSession` is enabled by adding a Servlet Filter before anything that uses the `HttpSession`. + +This section describes how to use Hazelcast to back `HttpSession` by using Java-based configuration. + +NOTE: The xref:samples.adoc#samples[ Hazelcast Spring Sample] provides a working sample of how to integrate Spring Session and `HttpSession` by using Java configuration. +You can read the basic steps for integration in the next few sections, but we encourage you to follow along with the detailed Hazelcast Spring Guide when integrating with your own application. + +include::guides/java-hazelcast.adoc[tags=config,leveloffset=+1] + +[[httpsession-how]] +== How `HttpSession` Integration Works + +Fortunately, both `HttpSession` and `HttpServletRequest` (the API for obtaining an `HttpSession`) are both interfaces. +This means that we can provide our own implementations for each of these APIs. + +NOTE: This section describes how Spring Session provides transparent integration with `HttpSession`. We offer this content so that you can understand what is happening under the covers. This functionality is already integrated and you do NOT need to implement this logic yourself. + +First, we create a custom `HttpServletRequest` that returns a custom implementation of `HttpSession`. +It looks something like the following: + +==== +[source, java] +---- +public class SessionRepositoryRequestWrapper extends HttpServletRequestWrapper { + + public SessionRepositoryRequestWrapper(HttpServletRequest original) { + super(original); + } + + public HttpSession getSession() { + return getSession(true); + } + + public HttpSession getSession(boolean createNew) { + // create an HttpSession implementation from Spring Session + } + + // ... other methods delegate to the original HttpServletRequest ... +} +---- +==== + +Any method that returns an `HttpSession` is overridden. +All other methods are implemented by `HttpServletRequestWrapper` and delegate to the original `HttpServletRequest` implementation. + +We replace the `HttpServletRequest` implementation by using a servlet `Filter` called `SessionRepositoryFilter`. +The following pseudocode shows how it works: + +==== +[source, java] +---- +public class SessionRepositoryFilter implements Filter { + + public doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { + HttpServletRequest httpRequest = (HttpServletRequest) request; + SessionRepositoryRequestWrapper customRequest = + new SessionRepositoryRequestWrapper(httpRequest); + + chain.doFilter(customRequest, response, chain); + } + + // ... +} +---- +==== + +By passing a custom `HttpServletRequest` implementation into the `FilterChain`, we ensure that anything invoked after our `Filter` uses the custom `HttpSession` implementation. +This highlights why it is important that Spring Session's `SessionRepositoryFilter` be placed before anything that interacts with the `HttpSession`. + +[[httpsession-rest]] +== `HttpSession` and RESTful APIs + +Spring Session can work with RESTful APIs by letting the session be provided in a header. + +NOTE: The xref:samples.adoc#samples[ REST Sample] provides a working sample of how to use Spring Session in a REST application to support authenticating with a header. +You can follow the basic steps for integration described in the next few sections, but we encourage you to follow along with the detailed REST Guide when integrating with your own application. + +include::guides/java-rest.adoc[tags=config,leveloffset=+1] + +[[httpsession-httpsessionlistener]] +== Using `HttpSessionListener` + +Spring Session supports `HttpSessionListener` by translating `SessionDestroyedEvent` and `SessionCreatedEvent` into `HttpSessionEvent` by declaring `SessionEventHttpSessionListenerAdapter`. +To use this support, you need to: + +* Ensure your `SessionRepository` implementation supports and is configured to fire `SessionDestroyedEvent` and `SessionCreatedEvent`. +* Configure `SessionEventHttpSessionListenerAdapter` as a Spring bean. +* Inject every `HttpSessionListener` into the `SessionEventHttpSessionListenerAdapter` + +If you use the configuration support documented in <>, all you need to do is register every `HttpSessionListener` as a bean. +For example, assume you want to support Spring Security's concurrency control and need to use `HttpSessionEventPublisher`. In that case, you can add `HttpSessionEventPublisher` as a bean. +In Java configuration, this might look like the following: + +==== +[source,java,indent=0] +---- +include::{docs-test-dir}docs/http/RedisHttpSessionConfig.java[tags=config] +---- +==== + +In XML configuration, this might look like the following: + +==== +[source,xml,indent=0] +---- +include::{docs-test-resources-dir}docs/http/HttpSessionListenerXmlTests-context.xml[tags=config] +---- +==== diff --git a/spring-session-docs/modules/ROOT/pages/index.adoc b/spring-session-docs/modules/ROOT/pages/index.adoc new file mode 100644 index 00000000..9cd3be32 --- /dev/null +++ b/spring-session-docs/modules/ROOT/pages/index.adoc @@ -0,0 +1,74 @@ += Spring Session +Rob Winch; Vedran Pavić; Jay Bryant; Eleftheria Stein-Kousathana +:doctype: book +:indexdoc-tests: {docs-test-dir}docs/IndexDocTests.java +:websocketdoc-test-dir: {docs-test-dir}docs/websocket/ + +[[abstract]] +Spring Session provides an API and implementations for managing a user's session information. + +[[introduction]] +Spring Session provides an API and implementations for managing a user's session information while also making it trivial to support clustered sessions without being tied to an application container-specific solution. +It also provides transparent integration with: + +* xref:http-session.adoc#httpsession[HttpSession]: Allows replacing the `HttpSession` in an application container-neutral way, with support for providing session IDs in headers to work with RESTful APIs. +* xref:web-socket.adoc#websocket[WebSocket]: Provides the ability to keep the `HttpSession` alive when receiving WebSocket messages +* xref:web-session.adoc#websession[WebSession]: Allows replacing the Spring WebFlux's `WebSession` in an application container-neutral way. + + +[[community]] +== Spring Session Community + +We are glad to consider you a part of our community. +The following sections provide additional about how to interact with the Spring Session community. + +[[community-support]] +=== Support + +You can get help by asking questions on https://stackoverflow.com/questions/tagged/spring-session[Stack Overflow with the `spring-session` tag]. +Similarly, we encourage helping others by answering questions on Stack Overflow. + +[[community-source]] +=== Source Code + +You can find the source code on GitHub at https://github.com/spring-projects/spring-session/ + +[[community-issues]] +=== Issue Tracking + +We track issues in GitHub issues at https://github.com/spring-projects/spring-session/issues + +[[community-contributing]] +=== Contributing + +We appreciate https://help.github.com/articles/using-pull-requests/[pull requests]. + +[[community-license]] +=== License + +Spring Session is Open Source software released under the https://www.apache.org/licenses/LICENSE-2.0[Apache 2.0 license]. + +[[community-extensions]] +=== Community Extensions + +|=== +| Name | Location + +| Spring Session Infinispan +| https://infinispan.org/infinispan-spring-boot/master/spring_boot_starter.html#_enabling_spring_session_support + +|=== + +[[minimum-requirements]] +== Minimum Requirements + +The minimum requirements for Spring Session are: + +* Java 8+. +* If you run in a Servlet Container (not required), Servlet 3.1+. +* If you use other Spring libraries (not required), the minimum required version is Spring 5.0.x. +* `@EnableRedisHttpSession` requires Redis 2.8+. This is necessary to support xref:api.adoc#api-redisindexedsessionrepository-expiration[Session Expiration] +* `@EnableHazelcastHttpSession` requires Hazelcast 3.6+. This is necessary to support xref:api.adoc#api-enablehazelcasthttpsession-storage[`FindByIndexNameSessionRepository`] + +NOTE: At its core, Spring Session has a required dependency only on `spring-jcl`. +For an example of using Spring Session without any other Spring dependencies, see the xref:samples.adoc#samples[hazelcast sample] application. diff --git a/spring-session-docs/modules/ROOT/pages/modules.adoc b/spring-session-docs/modules/ROOT/pages/modules.adoc new file mode 100644 index 00000000..50800bd2 --- /dev/null +++ b/spring-session-docs/modules/ROOT/pages/modules.adoc @@ -0,0 +1,23 @@ +[[modules]] += Spring Session Modules + +In Spring Session 1.x, all of the Spring Session's `SessionRepository` implementations were available within the `spring-session` artifact. +While convenient, this approach was not sustainable long-term as more features and `SessionRepository` implementations were added to the project. + +Starting with Spring Session 2.0, the project has been split into Spring Session Core module and several other modules that carry `SessionRepository` implementations and functionality related to the specific data store. +Users of Spring Data should find this arrangement familiar, with Spring Session Core module taking a role equivalent to Spring Data Commons and providing core functionalities and APIs, with other modules containing data store specific implementations. +As part of this split, the Spring Session Data MongoDB and Spring Session Data GemFire modules were moved to separate repositories. +Now the situation with project's repositories/modules is as follows: + +* https://github.com/spring-projects/spring-session[`spring-session` repository] +** Hosts the Spring Session Core, Spring Session Data Redis, Spring Session JDBC, and Spring Session Hazelcast modules +* https://github.com/spring-projects/spring-session-data-mongodb[`spring-session-data-mongodb` repository] +** Hosts the Spring Session Data MongoDB module. Spring Session Data MongoDB has its own user guide, which you can find at the [https://spring.io/projects/spring-session-data-mongodb#learnSpring site]. + +* https://github.com/spring-projects/spring-session-data-geode[`spring-session-data-geode` repository] +** Hosts the Spring Session Data Geode modules. Spring Session Data Geode has its own user guide, which you can find at the [https://spring.io/projects/spring-session-data-geode#learn site]. + +Finally, Spring Session now also provides a Maven BOM ("`bill of materials`") module in order to help users with version management concerns: + +* https://github.com/spring-projects/spring-session-bom[`spring-session-bom` repository] +** Hosts the Spring Session BOM module diff --git a/spring-session-docs/modules/ROOT/pages/samples.adoc b/spring-session-docs/modules/ROOT/pages/samples.adoc new file mode 100644 index 00000000..8646d090 --- /dev/null +++ b/spring-session-docs/modules/ROOT/pages/samples.adoc @@ -0,0 +1,100 @@ +[[samples]] += Samples and Guides (Start Here) + +To get started with Spring Session, the best place to start is our Sample Applications. + +.Sample Applications that use Spring Boot +|=== +| Source | Description | Guide + +| {gh-samples-url}spring-session-sample-boot-redis[HttpSession with Redis] +| Demonstrates how to use Spring Session to replace the `HttpSession` with Redis. +| link:guides/boot-redis.html[HttpSession with Redis Guide] + +| {gh-samples-url}spring-session-sample-boot-jdbc[HttpSession with JDBC] +| Demonstrates how to use Spring Session to replace the `HttpSession` with a relational database store. +| link:guides/boot-jdbc.html[HttpSession with JDBC Guide] + +| {gh-samples-url}spring-session-sample-boot-hazelcast[HttpSession with Hazelcast] +| Demonstrates how to use Spring Session to replace the `HttpSession` with Hazelcast. +| + +| {gh-samples-url}spring-session-sample-boot-findbyusername[Find by Username] +| Demonstrates how to use Spring Session to find sessions by username. +| link:guides/boot-findbyusername.html[Find by Username Guide] + +| {gh-samples-url}spring-session-sample-boot-websocket[WebSockets] +| Demonstrates how to use Spring Session with WebSockets. +| link:guides/boot-websocket.html[WebSockets Guide] + +| {gh-samples-url}spring-session-sample-boot-webflux[WebFlux] +| Demonstrates how to use Spring Session to replace the Spring WebFlux's `WebSession` with Redis. +| + +| {gh-samples-url}spring-session-sample-boot-webflux-custom-cookie[WebFlux with Custom Cookie] +| Demonstrates how to use Spring Session to customize the Session cookie in a WebFlux based application. +| link:guides/boot-webflux-custom-cookie.html[WebFlux with Custom Cookie Guide] + +| {gh-samples-url}spring-session-sample-boot-redis-json[HttpSession with Redis JSON serialization] +| Demonstrates how to use Spring Session to replace the `HttpSession` with Redis using JSON serialization. +| + +| {gh-samples-url}spring-session-sample-boot-redis-simple[HttpSession with simple Redis `SessionRepository`] +| Demonstrates how to use Spring Session to replace the `HttpSession` with Redis using `RedisSessionRepository`. +| + +|=== + +.Sample Applications that use Spring Java-based configuration +|=== +| Source | Description | Guide + +| {gh-samples-url}spring-session-sample-javaconfig-redis[HttpSession with Redis] +| Demonstrates how to use Spring Session to replace the `HttpSession` with Redis. +| link:guides/java-redis.html[HttpSession with Redis Guide] + +| {gh-samples-url}spring-session-sample-javaconfig-jdbc[HttpSession with JDBC] +| Demonstrates how to use Spring Session to replace the `HttpSession` with a relational database store. +| link:guides/java-jdbc.html[HttpSession with JDBC Guide] + +| {gh-samples-url}spring-session-sample-javaconfig-hazelcast[HttpSession with Hazelcast] +| Demonstrates how to use Spring Session to replace the `HttpSession` with Hazelcast. +| link:guides/java-hazelcast.html[HttpSession with Hazelcast Guide] + +| {gh-samples-url}spring-session-sample-javaconfig-custom-cookie[Custom Cookie] +| Demonstrates how to use Spring Session and customize the cookie. +| link:guides/java-custom-cookie.html[Custom Cookie Guide] + +| {gh-samples-url}spring-session-sample-javaconfig-security[Spring Security] +| Demonstrates how to use Spring Session with an existing Spring Security application. +| link:guides/java-security.html[Spring Security Guide] + +| {gh-samples-url}spring-session-sample-javaconfig-rest[REST] +| Demonstrates how to use Spring Session in a REST application to support authenticating with a header. +| link:guides/java-rest.html[REST Guide] + +|=== + +.Sample Applications that use Spring XML-based configuration +|=== +| Source | Description | Guide + +| {gh-samples-url}spring-session-sample-xml-redis[HttpSession with Redis] +| Demonstrates how to use Spring Session to replace the `HttpSession` with a Redis store. +| link:guides/xml-redis.html[HttpSession with Redis Guide] + +| {gh-samples-url}spring-session-sample-xml-jdbc[HttpSession with JDBC] +| Demonstrates how to use Spring Session to replace the `HttpSession` with a relational database store. +| link:guides/xml-jdbc.html[HttpSession with JDBC Guide] + +|=== + +.Miscellaneous sample Applications +|=== +| Source | Description | Guide + +| {gh-samples-url}spring-session-sample-misc-hazelcast[Hazelcast] +| Demonstrates how to use Spring Session with Hazelcast in a Java EE application. +| + +|=== diff --git a/spring-session-docs/modules/ROOT/pages/spring-security.adoc b/spring-session-docs/modules/ROOT/pages/spring-security.adoc new file mode 100644 index 00000000..3d7f614c --- /dev/null +++ b/spring-session-docs/modules/ROOT/pages/spring-security.adoc @@ -0,0 +1,77 @@ +[[spring-security]] += Spring Security Integration + +Spring Session provides integration with Spring Security. + +[[spring-security-rememberme]] +== Spring Security Remember-me Support + +Spring Session provides integration with https://docs.spring.io/spring-security/site/docs/{spring-security-version}/reference/htmlsingle/#remember-me[Spring Security's Remember-me Authentication]. +The support: + +* Changes the session expiration length +* Ensures that the session cookie expires at `Integer.MAX_VALUE`. +The cookie expiration is set to the largest possible value, because the cookie is set only when the session is created. +If it were set to the same value as the session expiration, the session would get renewed when the user used it but the cookie expiration would not be updated (causing the expiration to be fixed). + +To configure Spring Session with Spring Security in Java Configuration, you can use the following listing as a guide: + +==== +[source,java,indent=0] +---- +include::{docs-test-dir}docs/security/RememberMeSecurityConfiguration.java[tags=http-rememberme] + } + +include::{docs-test-dir}docs/security/RememberMeSecurityConfiguration.java[tags=rememberme-bean] +---- +==== + +An XML-based configuration would look something like the following: + +==== +[source,xml,indent=0] +---- +include::{docs-test-resources-dir}docs/security/RememberMeSecurityConfigurationXmlTests-context.xml[tags=config] +---- +==== + +[[spring-security-concurrent-sessions]] +== Spring Security Concurrent Session Control + + +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 also works in a clustered environment. This is done by providing a custom +implementation of Spring Security's `SessionRegistry` interface. + +When using Spring Security's Java config DSL, you can configure the custom `SessionRegistry` through the +`SessionManagementConfigurer`, as the following listing shows: + +==== +[source,java,indent=0] +---- +include::{docs-test-dir}docs/security/SecurityConfiguration.java[tags=class] +---- +==== + +This assumes that you have also configured Spring Session to provide a `FindByIndexNameSessionRepository` that +returns `Session` instances. + +When using XML configuration, it would look something like the following listing: + +==== +[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. + +[[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 by using Spring Session. This method is never called by Spring Security, +so this affects only applications that access the `SessionRegistry` themselves. diff --git a/spring-session-docs/modules/ROOT/pages/upgrading.adoc b/spring-session-docs/modules/ROOT/pages/upgrading.adoc new file mode 100644 index 00000000..c97a33b7 --- /dev/null +++ b/spring-session-docs/modules/ROOT/pages/upgrading.adoc @@ -0,0 +1,50 @@ +[[upgrading-2.0]] += Upgrading to 2.x + +With the new major release version, the Spring Session team took the opportunity to make some non-passive changes. +The focus of these changes is to improve and harmonize Spring Session's APIs as well as remove the deprecated components. + +== Baseline Update + +Spring Session 2.0 requires Java 8 and Spring Framework 5.0 as a baseline, since its entire codebase is now based on Java 8 source code. +See https://github.com/spring-projects/spring-framework/wiki/Upgrading-to-Spring-Framework-5.x[Upgrading to Spring Framework 5.x] for more on upgrading Spring Framework. + +== Replaced and Removed Modules + +As a part of the project's splitting of the modules, the existing `spring-session` has been replaced with the `spring-session-core` module. +The `spring-session-core` module holds only the common set of APIs and components, while other modules contain the implementation of the appropriate `SessionRepository` and functionality related to that data store. +This applies to several existing modules that were previously a simple dependency aggregator helper module. +With new module arrangement, the following modules actually carry the implementation: + +* Spring Session Data Redis +* Spring Session JDBC +* Spring Session Hazelcast + +Also, the following modules were removed from the main project repository: + +* Spring Session Data MongoDB +* Spring Session Data GemFire + +Note that these two have moved to separate repositories and continue to be available under new artifact names: + +* https://github.com/spring-projects/spring-session-data-mongodb[`spring-session-data-mongodb`] +* https://github.com/spring-projects/spring-session-data-geode[`spring-session-data-geode`] + +== Replaced and Removed Packages, Classes, and Methods + +The following changes were made to packages, classes, and methods: + +* `ExpiringSession` API has been merged into the `Session` API. +* The `Session` API has been enhanced to make full use of Java 8. +* The `Session` API has been extended with `changeSessionId` support. +* The `SessionRepository` API has been updated to better align with Spring Data method naming conventions. +* `AbstractSessionEvent` and its subclasses are no longer constructable without an underlying `Session` object. +* The Redis namespace used by `RedisOperationsSessionRepository` is now fully configurable, instead of being partially configurable. +* Redis configuration support has been updated to avoid registering a Spring Session-specific `RedisTemplate` bean. +* JDBC configuration support has been updated to avoid registering a Spring Session-specific `JdbcTemplate` bean. +* Previously deprecated classes and methods have been removed across the codebase + +== Dropped Support + +As a part of the changes to `HttpSessionStrategy` and its alignment to the counterpart from the reactive world, the support for managing multiple users' sessions in a single browser instance has been removed. +The introduction of a new API to replace this functionality is under consideration for future releases. diff --git a/spring-session-docs/modules/ROOT/pages/web-session.adoc b/spring-session-docs/modules/ROOT/pages/web-session.adoc new file mode 100644 index 00000000..c33dc268 --- /dev/null +++ b/spring-session-docs/modules/ROOT/pages/web-session.adoc @@ -0,0 +1,116 @@ + +[[websession]] += WebSession Integration + +Spring Session provides transparent integration with Spring WebFlux's `WebSession`. +This means that you can switch the `WebSession` implementation out with an implementation that is backed by Spring Session. + +[[websession-why]] +== Why Spring Session and WebSession? + +We have already mentioned that Spring Session provides transparent integration with Spring WebFlux's `WebSession`, but what benefits do we get out of this? +As with `HttpSession`, Spring Session makes it trivial to support <> without being tied to an application container specific solution. + +[[websession-redis]] +== WebSession with Redis + +Using Spring Session with `WebSession` is enabled by registering a `WebSessionManager` implementation backed by Spring Session's `ReactiveSessionRepository`. +The Spring configuration is responsible for creating a `WebSessionManager` that replaces the `WebSession` implementation with an implementation backed by Spring Session. +To do so, add the following Spring Configuration: + +==== +[source, java] +---- +@EnableRedisWebSession // <1> +public class SessionConfiguration { + + @Bean + public LettuceConnectionFactory redisConnectionFactory() { + return new LettuceConnectionFactory(); // <2> + } + +} +---- + +<1> The `@EnableRedisWebSession` annotation creates a Spring bean with the name of `webSessionManager`. That bean implements the `WebSessionManager`. +This is what is in charge of replacing the `WebSession` implementation to be backed by Spring Session. +In this instance, Spring Session is backed by Redis. +<2> We create a `RedisConnectionFactory` that connects Spring Session to the Redis Server. +We configure the connection to connect to localhost on the default port (6379) +For more information on configuring Spring Data Redis, see the https://docs.spring.io/spring-data/data-redis/docs/{spring-data-redis-version}/reference/html/[reference documentation]. +==== + +[[websession-how]] +== How WebSession Integration Works + +It is considerably easier for Spring Session to integrate with Spring WebFlux and its `WebSession`, compared to Servlet API and its `HttpSession`. +Spring WebFlux provides the `WebSessionStore` API, which presents a strategy for persisting `WebSession`. + +NOTE: This section describes how Spring Session provides transparent integration with `WebSession`. We offer this content so that you can understand what is happening under the covers. This functionality is already integrated and you do NOT need to implement this logic yourself. + +First, we create a custom `SpringSessionWebSession` that delegates to Spring Session's `Session`. +It looks something like the following: + +==== +[source, java] +---- +public class SpringSessionWebSession implements WebSession { + + enum State { + NEW, STARTED + } + + private final S session; + + private AtomicReference state = new AtomicReference<>(); + + SpringSessionWebSession(S session, State state) { + this.session = session; + this.state.set(state); + } + + @Override + public void start() { + this.state.compareAndSet(State.NEW, State.STARTED); + } + + @Override + public boolean isStarted() { + State value = this.state.get(); + return (State.STARTED.equals(value) + || (State.NEW.equals(value) && !this.session.getAttributes().isEmpty())); + } + + @Override + public Mono changeSessionId() { + return Mono.defer(() -> { + this.session.changeSessionId(); + return save(); + }); + } + + // ... other methods delegate to the original Session +} +---- +==== + +Next, we create a custom `WebSessionStore` that delegates to the `ReactiveSessionRepository` and wraps `Session` into custom `WebSession` implementation, as the following listing shows: + +==== +[source, java] +---- +public class SpringSessionWebSessionStore implements WebSessionStore { + + private final ReactiveSessionRepository sessions; + + public SpringSessionWebSessionStore(ReactiveSessionRepository reactiveSessionRepository) { + this.sessions = reactiveSessionRepository; + } + + // ... +} +---- +==== + +To be detected by Spring WebFlux, this custom `WebSessionStore` needs to be registered with `ApplicationContext` as a bean named `webSessionManager`. +For additional information on Spring WebFlux, see the https://docs.spring.io/spring-framework/docs/{spring-framework-version}/reference/html/web-reactive.html[Spring Framework Reference Documentation]. diff --git a/spring-session-docs/modules/ROOT/pages/web-socket.adoc b/spring-session-docs/modules/ROOT/pages/web-socket.adoc new file mode 100644 index 00000000..af1f1daf --- /dev/null +++ b/spring-session-docs/modules/ROOT/pages/web-socket.adoc @@ -0,0 +1,32 @@ +[[websocket]] += WebSocket Integration + +Spring Session provides transparent integration with Spring's WebSocket support. + +include::guides/boot-websocket.adoc[tags=disclaimer,leveloffset=+1] + +[[websocket-why]] +== Why Spring Session and WebSockets? + +So why do we need Spring Session when we use WebSockets? + +Consider an email application that does much of its work through HTTP requests. +However, there is also a chat application embedded within it that works over WebSocket APIs. +If a user is actively chatting with someone, we should not timeout the `HttpSession`, since this would be a pretty poor user experience. +However, this is exactly what https://java.net/jira/browse/WEBSOCKET_SPEC-175[JSR-356] does. + +Another issue is that, according to JSR-356, if the `HttpSession` times out, any WebSocket that was created with that `HttpSession` and an authenticated user should be forcibly closed. +This means that, if we are actively chatting in our application and are not using the HttpSession, we also do disconnect from our conversation. + +[[websocket-usage]] +== WebSocket Usage + +The xref:samples.adoc#samples[ WebSocket Sample] provides a working sample of how to integrate Spring Session with WebSockets. +You can follow the basic steps for integration described in the next few headings, but we encourage you to follow along with the detailed WebSocket Guide when integrating with your own application. + +[[websocket-httpsession]] +=== `HttpSession` Integration + +Before using WebSocket integration, you should be sure that you have xref:http-session.adoc#httpsession[`HttpSession` Integration] working first. + +include::guides/boot-websocket.adoc[tags=config,leveloffset=+2] diff --git a/spring-session-docs/modules/ROOT/pages/whats-new.adoc b/spring-session-docs/modules/ROOT/pages/whats-new.adoc new file mode 100644 index 00000000..b80da238 --- /dev/null +++ b/spring-session-docs/modules/ROOT/pages/whats-new.adoc @@ -0,0 +1,4 @@ += What's New + +Check also the Spring Session BOM https://github.com/spring-projects/spring-session-bom/wiki#release-notes[release notes] +for a list of new and noteworthy features, as well as upgrade instructions for each release. diff --git a/spring-session-docs/spring-session-docs.gradle b/spring-session-docs/spring-session-docs.gradle index 355ed426..eadc6de8 100644 --- a/spring-session-docs/spring-session-docs.gradle +++ b/spring-session-docs/spring-session-docs.gradle @@ -23,8 +23,59 @@ dependencies { testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine' } +sourceSets { + test { + java { + srcDirs = ['modules/ROOT/examples/java'] + } + resources { + srcDirs = ['modules/ROOT/examples/resources'] + } + } +} + def versions = dependencyManagement.managedVersions + +tasks.register("generateAntora") { + group = "Documentation" + description = "Generates the antora.yml for dynamic properties" + doLast { + def dollar = '$' + def ghTag = snapshotBuild ? 'main' : project.version + def ghUrl = "https://github.com/spring-projects/spring-session/tree/$ghTag" + def outputFile = new File("$buildDir/generateAntora/antora.yml") + outputFile.getParentFile().mkdirs() + outputFile.createNewFile() + outputFile.setText("""name: session +title: Spring Session +version: ~ +display_version: 2.6 +start_page: ROOT:index.adoc +asciidoc: + attributes: + download-url: "https://github.com/spring-projects/spring-session/archive/${ghTag}.zip" + gh-samples-url: "$ghUrl/spring-session-samples/" + samples-dir: "example${dollar}spring-session-samples/" + session-jdbc-main-resources-dir: "example${dollar}session-jdbc-main-resources-dir/" + docs-test-dir: "example${dollar}java/" + websocketdoc-test-dir: 'example${dollar}java/docs/websocket/' + docs-test-resources-dir: "example${dollar}resources/" + indexdoc-tests: "example${dollar}java/docs/IndexDocTests.java" + spring-session-version: ${project.version} + version-milestone: $milestoneBuild + version-release: $releaseBuild + version-snapshot: $snapshotBuild + spring-boot-version: ${project.springBootVersion} + spring-data-redis-version: ${versions['org.springframework.data:spring-data-redis']} + spring-framework-version: ${versions['org.springframework:spring-core']} + spring-security-version: ${versions['org.springframework.security:spring-security-core']} + hazelcast-version: ${versions['com.hazelcast:hazelcast']} + lettuce-version: ${versions['io.lettuce:lettuce-core']} +""") + } +} + asciidoctorPdf { clearSources() sources { diff --git a/spring-session-samples/spring-session-sample-boot-websocket/src/main/resources/application.properties b/spring-session-samples/spring-session-sample-boot-websocket/src/main/resources/application.properties index 62c01000..bfdecd49 100644 --- a/spring-session-samples/spring-session-sample-boot-websocket/src/main/resources/application.properties +++ b/spring-session-samples/spring-session-sample-boot-websocket/src/main/resources/application.properties @@ -1,3 +1,2 @@ #server.servlet.session.timeout=1m spring.h2.console.enabled=true -spring.jpa.defer-datasource-initialization=true