diff --git a/docs/src/docs/asciidoc/guides/boot-findbyusername.adoc b/docs/src/docs/asciidoc/guides/boot-findbyusername.adoc index 9da37821..a0de619a 100644 --- a/docs/src/docs/asciidoc/guides/boot-findbyusername.adoc +++ b/docs/src/docs/asciidoc/guides/boot-findbyusername.adoc @@ -4,137 +4,141 @@ Rob Winch This guide describes how to use Spring Session to find sessions by username. -NOTE: The completed guide can be found in the <>. +NOTE: You can find the completed guide in the <>. [[findbyusername-assumptions]] == Assumptions -The guide assumes you have already added Spring Session using the built in Redis configuration support to your application. +The guide assumes you have already added Spring Session to your application by using the built-in Redis configuration support. The guide also assumes you have already applied Spring Security to your application. -However, we the guide will be somewhat general purpose and can be applied to any technology with minimal changes we will discuss. +However, we the guide is somewhat general purpose and can be applied to any technology with minimal changes, which we discuss later in the guide. -[NOTE] -==== -If you need to learn how to add Spring Session to your project, please refer to the listing of link:../#samples[samples and guides] -==== +NOTE: If you need to learn how to add Spring Session to your project, see the listing of link:../#samples[samples and guides] == About the Sample -Our sample is using this feature to invalidate the users session that might have been compromised. +Our sample uses this feature to invalidate the users session that might have been compromised. Consider the following scenario: -* User goes to library and authenticates to the application -* User goes home and realizes they forgot to log out -* User can log in and terminate the session from the library using clues like the location, created time, last accessed time, etc. +* User goes to library and authenticates to the application. +* User goes home and realizes they forgot to log out. +* User can log in and terminate the session from the library using clues like the location, created time, last accessed time, and so on. -Wouldn't it be nice if we could allow the user to invalidate the session at the library from any device they authenticate with? +Would it not be nice if we could let the user invalidate the session at the library from any device with which they authenticate? This sample demonstrates how this is possible. [[findbyindexnamesessionrepository]] -== FindByIndexNameSessionRepository +== Using `FindByIndexNameSessionRepository` -In order to look up a user by their username, you must first choose a `SessionRepository` that implements link:../#api-findbyindexnamesessionrepository[FindByIndexNameSessionRepository]. -Our sample application assumes that the Redis support is already setup, so we are ready to go. +To look up a user by their username, you must first choose a `SessionRepository` that implements link:../#api-findbyindexnamesessionrepository[`FindByIndexNameSessionRepository`]. +Our sample application assumes that the Redis support is already set up, so we are ready to go. -== Mapping the username +== Mapping the User Name -`FindByIndexNameSessionRepository` can only find a session by the username, if the developer instructs Spring Session what user is associated with the `Session`. -This is done by ensuring that the session attribute with the name `FindByUsernameSessionRepository.PRINCIPAL_NAME_INDEX_NAME` is populated with the username. +`FindByIndexNameSessionRepository` can find a session only by the user name if the developer instructs Spring Session what user is associated with the `Session`. +You can do so by ensuring that the session attribute with the name `FindByUsernameSessionRepository.PRINCIPAL_NAME_INDEX_NAME` is populated with the username. -Generally, speaking this can be done with the following code immediately after the user authenticates: +Generally speaking, you can do so with the following code immediately after the user authenticates: +==== [source,java,indent=0] ---- include::{docs-test-dir}docs/FindByIndexNameSessionRepositoryTests.java[tags=set-username] ---- +==== -== Mapping the username with Spring Security +== Mapping the User Name with Spring Security -Since we are using Spring Security, the user name is automatically indexed for us. -This means we will not have to perform any steps to ensure the user name is indexed. +Since we use Spring Security, the user name is automatically indexed for us. +This means we need not perform any steps to ensure the user name is indexed. -== Adding Additional Data to Session +== Adding Additional Data to the Session -It may be nice to associate additional information (i.e. IP Address, the browser, location, etc) to the session. -This makes it easier for the user to know which session they are looking at. +It may be nice to associate additional information (such as the IP Address, the browser, location, and other details) to the session. +Doing so makes it easier for the user to know which session they are looking at. -To do this simply determine which session attribute you want to use and what information you wish to provide. +To do so, determine which session attribute you want to use and what information you wish to provide. Then create a Java bean that is added as a session attribute. -For example, our sample application includes the location and access type of the session +For example, our sample application includes the location and access type of the session, as the following listing shows: +==== [source,java,indent=0] ---- include::{samples-dir}boot/findbyusername/src/main/java/sample/session/SessionDetails.java[tags=class] ---- +==== -We then inject that information into the session on each HTTP request using a `SessionDetailsFilter`. -For example: +We then inject that information into the session on each HTTP request using a `SessionDetailsFilter`, as the following example shows: +==== [source,java,indent=0] ---- include::{samples-dir}boot/findbyusername/src/main/java/sample/session/SessionDetailsFilter.java[tags=dofilterinternal] ---- +==== We obtain the information we want and then set the `SessionDetails` as an attribute in the `Session`. -When we retrieve the `Session` by username, we can then use the session to access our `SessionDetails` just like any other session attribute. +When we retrieve the `Session` by user name, we can then use the session to access our `SessionDetails` as we would any other session attribute. -[NOTE] -==== -You might be wondering at this point why Spring Session does not provide `SessionDetails` functionality out of the box. -The reason, is twofold. -The first is that it is very trivial for applications to implement this themselves. -The second reason is that the information that is populated in the session (and how frequently that information is updated) is highly application dependent. -==== +NOTE: You might wonder why Spring Session does not provide `SessionDetails` functionality out of the box. +We have two reasons. +The first reason is that it is very trivial for applications to implement this themselves. +The second reason is that the information that is populated in the session (and how frequently that information is updated) is highly application-dependent. == Finding sessions for a specific user We can now find all the sessions for a specific user. +The following example shows how to do so: +==== [source,java,indent=0] ---- include::{samples-dir}boot/findbyusername/src/main/java/sample/mvc/IndexController.java[tags=findbyusername] ---- +==== In our instance, we find all sessions for the currently logged in user. -However, this could easily be modified for an administrator to use a form to specify which user to look up. +However, you can modify this for an administrator to use a form to specify which user to look up. [[findbyusername-sample]] -== findbyusername Sample Application +== `findbyusername` Sample Application -=== Running the findbyusername Sample Application +This section describes how to use the `findbyusername` sample application. + +=== Running the `findbyusername` Sample Application You can run the sample by obtaining the {download-url}[source code] and invoking the following command: -[NOTE] ==== -For the sample to work, you must https://redis.io/download[install Redis 2.8+] on localhost and run it with the default port (6379). -Alternatively, you can update the `RedisConnectionFactory` to point to a Redis server. -Another option is to use https://www.docker.com/[Docker] to run Redis on localhost. See https://hub.docker.com/_/redis/[Docker Redis repository] for detailed instructions. -==== - ---- $ ./gradlew :spring-session-sample-boot-findbyusername:bootRun ---- +==== + +NOTE: For the sample to work, you must https://redis.io/download[install Redis 2.8+] on localhost and run it with the default port (6379). +Alternatively, you can update the `RedisConnectionFactory` to point to a Redis server. +Another option is to use https://www.docker.com/[Docker] to run Redis on localhost. +See https://hub.docker.com/_/redis/[Docker Redis repository] for detailed instructions. You should now be able to access the application at http://localhost:8080/ === Exploring the security Sample Application -Try using the application. Enter the following to log in: +You can now try using the application. Enter the following to log in: -* **Username** _user_ -* **Password** _password_ +* *Username* _user_ +* *Password* _password_ -Now click the **Login** button. +Now click the *Login* button. You should now see a message indicating your are logged in with the user entered previously. You should also see a listing of active sessions for the currently logged in user. -Let's emulate the flow we discussed in the <> section +You can emulate the flow we discussed in the <> section by doing the following: * Open a new incognito window and navigate to http://localhost:8080/ * Enter the following to log in: -** **Username** _user_ -** **Password** _password_ -* Terminate your original session -* Refresh the original window and see you are logged out +** *Username* _user_ +** *Password* _password_ +* Terminate your original session. +* Refresh the original window and see that you are logged out. diff --git a/docs/src/docs/asciidoc/guides/boot-jdbc.adoc b/docs/src/docs/asciidoc/guides/boot-jdbc.adoc index 4c36eaf7..fd66bf68 100644 --- a/docs/src/docs/asciidoc/guides/boot-jdbc.adoc +++ b/docs/src/docs/asciidoc/guides/boot-jdbc.adoc @@ -2,15 +2,17 @@ Rob Winch, Vedran Pavić :toc: -This guide describes how to use Spring Session to transparently leverage a relational database to back a web application's `HttpSession` when using Spring Boot. +This guide describes how to use Spring Session to transparently leverage a relational database to back a web application's `HttpSession` when you use Spring Boot. -NOTE: The completed guide can be found in the <>. +NOTE: You can find the completed guide in the <>. == Updating Dependencies -Before you use Spring Session, you must ensure to update your dependencies. -We assume you are working with a working Spring Boot web application. -If you are using Maven, ensure to add the following dependencies: +Before you use Spring Session, you must update your dependencies. +We assume you are working with a working Spring Boot web application. +If you use Maven, you must add the following dependencies: + +==== .pom.xml [source,xml] [subs="verbatim,attributes"] @@ -24,8 +26,9 @@ If you are using Maven, ensure to add the following dependencies: ---- +==== -Spring Boot provides dependency management for Spring Session modules, so there's no need to explicitly declare dependency version. +Spring Boot provides dependency management for Spring Session modules, so you need not explicitly declare the dependency version. // tag::config[] @@ -33,95 +36,106 @@ Spring Boot provides dependency management for Spring Session modules, so there' == Spring Boot Configuration After adding the required dependencies, we can create our Spring Boot configuration. -Thanks to first-class auto configuration support, setting up Spring Session backed by a relational database is as simple as adding a single configuration property to your `application.properties`: +Thanks to first-class auto configuration support, setting up Spring Session backed by a relational database is as simple as adding a single configuration property to your `application.properties`. +The following listing shows how to do so: +==== .src/main/resources/application.properties ---- spring.session.store-type=jdbc # Session store type. ---- +==== -Under the hood, Spring Boot will apply configuration that is equivalent to manually adding `@EnableJdbcHttpSession` annotation. -This creates a Spring Bean with the name of `springSessionRepositoryFilter` that implements Filter. -The filter is what is in charge of replacing the `HttpSession` implementation to be backed by Spring Session. +Under the hood, Spring Boot applies configuration that is equivalent to manually adding the `@EnableJdbcHttpSession` annotation. +This creates a Spring bean with the name of `springSessionRepositoryFilter`. That bean implements `Filter`. +The filter is in charge of replacing the `HttpSession` implementation to be backed by Spring Session. -Further customization is possible using `application.properties`: +You can further customize by using `application.properties`. +The following listing shows how to do so: +==== .src/main/resources/application.properties ---- -server.servlet.session.timeout= # Session timeout. If a duration suffix is not specified, seconds will be used. +server.servlet.session.timeout= # Session timeout. If a duration suffix is not specified, seconds are used. spring.session.jdbc.initialize-schema=embedded # Database schema initialization mode. spring.session.jdbc.schema=classpath:org/springframework/session/jdbc/schema-@@platform@@.sql # Path to the SQL file to use to initialize the database schema. spring.session.jdbc.table-name=SPRING_SESSION # Name of the database table used to store sessions. ---- +==== -For more information, refer to https://docs.spring.io/spring-boot/docs/{spring-boot-version}/reference/htmlsingle/#boot-features-session[Spring Session] portion of the Spring Boot documentation. +For more information, see the https://docs.spring.io/spring-boot/docs/{spring-boot-version}/reference/htmlsingle/#boot-features-session[Spring Session] portion of the Spring Boot documentation. [[httpsession-jdbc-boot-configuration]] -== Configuring the DataSource +== Configuring the `DataSource` -Spring Boot automatically creates a `DataSource` that connects Spring Session to an embedded instance of H2 database. -In a production environment you need to ensure to update your configuration to point to your relational database. -For example, you can include the following in your *application.properties* +Spring Boot automatically creates a `DataSource` that connects Spring Session to an embedded instance of an H2 database. +In a production environment, you need to update your configuration to point to your relational database. +For example, you can include the following in your application.properties: +==== .src/main/resources/application.properties ---- spring.datasource.url= # JDBC URL of the database. spring.datasource.username= # Login username of the database. spring.datasource.password= # Login password of the database. ---- +==== -For more information, refer to https://docs.spring.io/spring-boot/docs/{spring-boot-version}/reference/htmlsingle/#boot-features-configure-datasource[Configure a DataSource] portion of the Spring Boot documentation. +For more information, see the https://docs.spring.io/spring-boot/docs/{spring-boot-version}/reference/htmlsingle/#boot-features-configure-datasource[Configure a DataSource] portion of the Spring Boot documentation. [[httpsession-jdbc-boot-servlet-configuration]] == Servlet Container Initialization -Our <> created a Spring Bean named `springSessionRepositoryFilter` that implements `Filter`. +Our <> 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 `Config` class. -Last we need to ensure that our Servlet Container (i.e. Tomcat) uses our `springSessionRepositoryFilter` for every request. +Last, we need to ensure that our Servlet Container (that is, Tomcat) uses our `springSessionRepositoryFilter` for every request. Fortunately, Spring Boot takes care of both of these steps for us. // end::config[] [[httpsession-jdbc-boot-sample]] -== httpsession-jdbc-boot Sample Application +== `httpsession-jdbc-boot` Sample Application -The httpsession-jdbc-boot Sample Application demonstrates how to use Spring Session to transparently leverage H2 database to back a web application's `HttpSession` when using Spring Boot. +The httpsession-jdbc-boot Sample Application demonstrates how to use Spring Session to transparently leverage an H2 database to back a web application's `HttpSession` when you use Spring Boot. [[httpsession-jdbc-boot-running]] -=== Running the httpsession-jdbc-boot Sample Application +=== Running the `httpsession-jdbc-boot` Sample Application You can run the sample by obtaining the {download-url}[source code] and invoking the following command: +==== ---- $ ./gradlew :spring-session-sample-boot-jdbc:bootRun ---- +==== You should now be able to access the application at http://localhost:8080/ [[httpsession-jdbc-boot-explore]] -=== Exploring the security Sample Application +=== Exploring the Security Sample Application -Try using the application. Enter the following to log in: +You can now try using the application. +To do so, enter the following to log in: -* **Username** _user_ -* **Password** _password_ +* *Username* _user_ +* *Password* _password_ -Now click the **Login** button. -You should now see a message indicating your are logged in with the user entered previously. -The user's information is stored in H2 database rather than Tomcat's `HttpSession` implementation. +Now click the *Login* button. +You should now see a message indicating that your are logged in with the user entered previously. +The user's information is stored in the H2 database rather than Tomcat's `HttpSession` implementation. [[httpsession-jdbc-boot-how]] -=== How does it work? +=== How Does It Work? -Instead of using Tomcat's `HttpSession`, we are actually persisting the values in H2 database. +Instead of using Tomcat's `HttpSession`, we persist the values in the H2 database. Spring Session replaces the `HttpSession` with an implementation that is backed by a relational database. -When Spring Security's `SecurityContextPersistenceFilter` saves the `SecurityContext` to the `HttpSession` it is then persisted into H2 database. +When Spring Security's `SecurityContextPersistenceFilter` saves the `SecurityContext` to the `HttpSession`, it is then persisted into the H2 database. -When a new `HttpSession` is created, Spring Session creates a cookie named SESSION in your browser that contains the id of your session. -Go ahead and view the cookies (click for help with https://developers.google.com/web/tools/chrome-devtools/manage-data/cookies[Chrome] or https://developer.mozilla.org/en-US/docs/Tools/Storage_Inspector[Firefox]). +When a new `HttpSession` is created, Spring Session creates a cookie named `SESSION` in your browser. That cookie contains the ID of your session. +You can view the cookies (with https://developers.google.com/web/tools/chrome-devtools/manage-data/cookies[Chrome] or https://developer.mozilla.org/en-US/docs/Tools/Storage_Inspector[Firefox]). -If you like, you can easily remove the session using H2 web console available at: http://localhost:8080/h2-console/ (use `jdbc:h2:mem:testdb` for JDBC URL) +You can remove the session by using the H2 web console available at: http://localhost:8080/h2-console/ (use `jdbc:h2:mem:testdb` for JDBC URL). -Now visit the application at http://localhost:8080/ and observe that we are no longer authenticated. +Now you can visit the application at http://localhost:8080/ and see that we are no longer authenticated. diff --git a/docs/src/docs/asciidoc/guides/boot-redis.adoc b/docs/src/docs/asciidoc/guides/boot-redis.adoc index d44485b7..8fb19bdd 100644 --- a/docs/src/docs/asciidoc/guides/boot-redis.adoc +++ b/docs/src/docs/asciidoc/guides/boot-redis.adoc @@ -2,15 +2,17 @@ Rob Winch, Vedran Pavić :toc: -This guide describes how to use Spring Session to transparently leverage Redis to back a web application's `HttpSession` when using Spring Boot. +This guide describes how to use Spring Session to transparently leverage Redis to back a web application's `HttpSession` when you use Spring Boot. -NOTE: The completed guide can be found in the <>. +NOTE: You can find the completed guide in the <>. == Updating Dependencies -Before you use Spring Session, you must ensure to update your dependencies. -We assume you are working with a working Spring Boot web application. -If you are using Maven, ensure to add the following dependencies: +Before you use Spring Session, you must ensure your dependencies. +We assume you are working with a working Spring Boot web application. +If you are using Maven, you must add the following dependencies: + +==== .pom.xml [source,xml] [subs="verbatim,attributes"] @@ -24,114 +26,131 @@ If you are using Maven, ensure to add the following dependencies: ---- +==== -Spring Boot provides dependency management for Spring Session modules, so there's no need to explicitly declare dependency version. +Spring Boot provides dependency management for Spring Session modules, so you need not explicitly declare dependency version. [[boot-spring-configuration]] == Spring Boot Configuration After adding the required dependencies, we can create our Spring Boot configuration. -Thanks to first-class auto configuration support, setting up Spring Session backed by Redis is as simple as adding a single configuration property to your `application.properties`: +Thanks to first-class auto configuration support, setting up Spring Session backed by Redis is as simple as adding a single configuration property to your `application.properties`, as the following listing shows: +==== .src/main/resources/application.properties ---- spring.session.store-type=redis # Session store type. ---- +==== -Under the hood, Spring Boot will apply configuration that is equivalent to manually adding `@EnableRedisHttpSession` annotation. -This creates a Spring Bean with the name of `springSessionRepositoryFilter` that implements Filter. -The filter is what is in charge of replacing the `HttpSession` implementation to be backed by Spring Session. +Under the hood, Spring Boot applies configuration that is equivalent to manually adding `@EnableRedisHttpSession` annotation. +This creates a Spring bean with the name of `springSessionRepositoryFilter` that implements `Filter`. +The filter is in charge of replacing the `HttpSession` implementation to be backed by Spring Session. -Further customization is possible using `application.properties`: +Further customization is possible by using `application.properties`, as the following listing shows: +==== .src/main/resources/application.properties ---- -server.servlet.session.timeout= # Session timeout. If a duration suffix is not specified, seconds will be used. +server.servlet.session.timeout= # Session timeout. If a duration suffix is not specified, seconds is used. spring.session.redis.flush-mode=on-save # Sessions flush mode. spring.session.redis.namespace=spring:session # Namespace for keys used to store sessions. ---- +==== -For more information, refer to https://docs.spring.io/spring-boot/docs/{spring-boot-version}/reference/htmlsingle/#boot-features-session[Spring Session] portion of the Spring Boot documentation. +For more information, see the https://docs.spring.io/spring-boot/docs/{spring-boot-version}/reference/htmlsingle/#boot-features-session[Spring Session] portion of the Spring Boot documentation. [[boot-redis-configuration]] == Configuring the Redis Connection Spring Boot automatically creates a `RedisConnectionFactory` that connects Spring Session to a Redis Server on localhost on port 6379 (default port). -In a production environment you need to ensure to update your configuration to point to your Redis server. -For example, you can include the following in your *application.properties* +In a production environment, you need to update your configuration to point to your Redis server. +For example, you can include the following in your application.properties: +==== .src/main/resources/application.properties ---- spring.redis.host=localhost # Redis server host. spring.redis.password= # Login password of the redis server. spring.redis.port=6379 # Redis server port. ---- +==== -For more information, refer to https://docs.spring.io/spring-boot/docs/{spring-boot-version}/reference/htmlsingle/#boot-features-connecting-to-redis[Connecting to Redis] portion of the Spring Boot documentation. +For more information, see the https://docs.spring.io/spring-boot/docs/{spring-boot-version}/reference/htmlsingle/#boot-features-connecting-to-redis[Connecting to Redis] portion of the Spring Boot documentation. [[boot-servlet-configuration]] == Servlet Container Initialization -Our <> created a Spring Bean named `springSessionRepositoryFilter` that implements `Filter`. +Our <> 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 `Config` class. -Last we need to ensure that our Servlet Container (i.e. Tomcat) uses our `springSessionRepositoryFilter` for every request. +Last, we need to ensure that our servlet container (that is, Tomcat) uses our `springSessionRepositoryFilter` for every request. Fortunately, Spring Boot takes care of both of these steps for us. [[boot-sample]] == Boot Sample Application -The Boot Sample Application demonstrates how to use Spring Session to transparently leverage Redis to back a web application's `HttpSession` when using Spring Boot. +The Boot Sample Application demonstrates how to use Spring Session to transparently leverage Redis to back a web application's `HttpSession` when you use Spring Boot. [[boot-running]] === Running the Boot Sample Application You can run the sample by obtaining the {download-url}[source code] and invoking the following command: -[NOTE] ==== -For the sample to work, you must https://redis.io/download[install Redis 2.8+] on localhost and run it with the default port (6379). -Alternatively, you can update the `RedisConnectionFactory` to point to a Redis server. -Another option is to use https://www.docker.com/[Docker] to run Redis on localhost. See https://hub.docker.com/_/redis/[Docker Redis repository] for detailed instructions. -==== - ---- $ ./gradlew :spring-session-sample-boot-redis:bootRun ---- +==== + +NOTE: For the sample to work, you must https://redis.io/download[install Redis 2.8+] on localhost and run it with the default port (6379). +Alternatively, you can update the `RedisConnectionFactory` to point to a Redis server. +Another option is to use https://www.docker.com/[Docker] to run Redis on localhost. See https://hub.docker.com/_/redis/[Docker Redis repository] for detailed instructions. You should now be able to access the application at http://localhost:8080/ [[boot-explore]] -=== Exploring the security Sample Application +=== Exploring the `security` Sample Application -Try using the application. Enter the following to log in: +Now you can try using the application. Enter the following to log in: -* **Username** _user_ -* **Password** _password_ +* *Username* _user_ +* *Password* _password_ -Now click the **Login** button. +Now click the *Login* button. You should now see a message indicating your are logged in with the user entered previously. The user's information is stored in Redis rather than Tomcat's `HttpSession` implementation. [[boot-how]] -=== How does it work? +=== How Does It Work? -Instead of using Tomcat's `HttpSession`, we are actually persisting the values in Redis. +Instead of using Tomcat's `HttpSession`, we persist the values in Redis. Spring Session replaces the `HttpSession` with an implementation that is backed by Redis. -When Spring Security's `SecurityContextPersistenceFilter` saves the `SecurityContext` to the `HttpSession` it is then persisted into Redis. +When Spring Security's `SecurityContextPersistenceFilter` saves the `SecurityContext` to the `HttpSession`, it is then persisted into Redis. -When a new `HttpSession` is created, Spring Session creates a cookie named SESSION in your browser that contains the id of your session. -Go ahead and view the cookies (click for help with https://developers.google.com/web/tools/chrome-devtools/manage-data/cookies[Chrome] or https://developer.mozilla.org/en-US/docs/Tools/Storage_Inspector[Firefox]). +When a new `HttpSession` is created, Spring Session creates a cookie named `SESSION` in your browser. +That cookie contains the ID of your session. +You can view the cookies (with https://developers.google.com/web/tools/chrome-devtools/manage-data/cookies[Chrome] or https://developer.mozilla.org/en-US/docs/Tools/Storage_Inspector[Firefox]). -If you like, you can easily remove the session using redis-cli. For example, on a Linux based system you can type: +You can remove the session by using redis-cli. +For example, on a Linux based system you can type the following: +==== +---- $ redis-cli keys '*' | xargs redis-cli del +---- +==== TIP: The Redis documentation has instructions for https://redis.io/topics/quickstart[installing redis-cli]. -Alternatively, you can also delete the explicit key. Enter the following into your terminal ensuring to replace `7e8383a4-082c-4ffe-a4bc-c40fd3363c5e` with the value of your SESSION cookie: +Alternatively, you can also delete the explicit key. +To do so, enter the following into your terminal, being sure to replace `7e8383a4-082c-4ffe-a4bc-c40fd3363c5e` with the value of your `SESSION` cookie: +==== +---- $ redis-cli del spring:session:sessions:7e8383a4-082c-4ffe-a4bc-c40fd3363c5e +---- +===== -Now visit the application at http://localhost:8080/ and observe that we are no longer authenticated. +Now you can visit the application at http://localhost:8080/ and observe that we are no longer authenticated. diff --git a/docs/src/docs/asciidoc/guides/boot-websocket.adoc b/docs/src/docs/asciidoc/guides/boot-websocket.adoc index 9354851e..e1bbbbce 100644 --- a/docs/src/docs/asciidoc/guides/boot-websocket.adoc +++ b/docs/src/docs/asciidoc/guides/boot-websocket.adoc @@ -7,9 +7,8 @@ This guide describes how to use Spring Session to ensure that WebSocket messages // tag::disclaimer[] -NOTE: Spring Session's WebSocket support only works with Spring's WebSocket support. -Specifically it does not work with using https://www.jcp.org/en/jsr/detail?id=356[JSR-356] directly. -This is due to the fact that JSR-356 does not have a mechanism for intercepting incoming WebSocket messages. +NOTE: Spring Session's WebSocket support works only with Spring's WebSocket support. +Specifically,it does not work with using https://www.jcp.org/en/jsr/detail?id=356[JSR-356] directly, because JSR-356 does not have a mechanism for intercepting incoming WebSocket messages. // end::disclaimer[] @@ -17,24 +16,27 @@ This is due to the fact that JSR-356 does not have a mechanism for intercepting The first step is to integrate Spring Session with the HttpSession. These steps are already outlined in the link:httpsession.html[HttpSession Guide]. -Please make sure you have already integrated Spring Session with the HttpSession before proceeding. +Please make sure you have already integrated Spring Session with HttpSession before proceeding. // tag::config[] [[websocket-spring-configuration]] == Spring Configuration -In a typical Spring WebSocket application users would implement `WebSocketMessageBrokerConfigurer`. +In a typical Spring WebSocket application, you would implement `WebSocketMessageBrokerConfigurer`. For example, the configuration might look something like the following: +==== [source,java] ---- include::{websocketdoc-test-dir}WebSocketConfig.java[tags=class] ---- +==== -We can easily update our configuration to use Spring Session's WebSocket support. -For example: +We can update our configuration to use Spring Session's WebSocket support. +The following example shows how to do so: +==== .src/main/java/samples/config/WebSocketConfig.java [source,java] ---- @@ -43,8 +45,9 @@ include::{samples-dir}boot/websocket/src/main/java/sample/config/WebSocketConfig To hook in the Spring Session support we only need to change two things: -<1> Instead of implementing `WebSocketMessageBrokerConfigurer` we extend `AbstractSessionWebSocketMessageBrokerConfigurer` +<1> Instead of implementing `WebSocketMessageBrokerConfigurer`, we extend `AbstractSessionWebSocketMessageBrokerConfigurer` <2> We rename the `registerStompEndpoints` method to `configureStompEndpoints` +==== What does `AbstractSessionWebSocketMessageBrokerConfigurer` do behind the scenes? @@ -52,87 +55,89 @@ What does `AbstractSessionWebSocketMessageBrokerConfigurer` do behind the scenes This ensures a custom `SessionConnectEvent` is fired that contains the `WebSocketSession`. The `WebSocketSession` is necessary to terminate any WebSocket connections that are still open when a Spring Session is terminated. * `SessionRepositoryMessageInterceptor` is added as a `HandshakeInterceptor` to every `StompWebSocketEndpointRegistration`. -This ensures that the Session is added to the WebSocket properties to enable updating the last accessed time. +This ensures that the `Session` is added to the WebSocket properties to enable updating the last accessed time. * `SessionRepositoryMessageInterceptor` is added as a `ChannelInterceptor` to our inbound `ChannelRegistration`. This ensures that every time an inbound message is received, that the last accessed time of our Spring Session is updated. -* `WebSocketRegistryListener` is created as a Spring Bean. -This ensures that we have a mapping of all of the Session id to the corresponding WebSocket connections. +* `WebSocketRegistryListener` is created as a Spring bean. +This ensures that we have a mapping of all of the `Session` IDs to the corresponding WebSocket connections. By maintaining this mapping, we can close all the WebSocket connections when a Spring Session (HttpSession) is terminated. // end::config[] [[websocket-sample]] -== websocket Sample Application +== `websocket` Sample Application -The websocket sample application demonstrates how to use Spring Session with WebSockets. +The `websocket` sample application demonstrates how to use Spring Session with WebSockets. -=== Running the websocket Sample Application +=== Running the `websocket` Sample Application You can run the sample by obtaining the {download-url}[source code] and invoking the following command: -[TIP] ==== -For the purposes of testing session expiration, you may want to change the session expiration to be 1 minute (default is 30 minutes) by adding the following configuration property starting before the application: +---- +$ ./gradlew :spring-session-sample-boot-websocket:bootRun +---- +==== +[TIP] +===== +For the purposes of testing session expiration, you may want to change the session expiration to be 1 minute (the default is 30 minutes) by adding the following configuration property before starting the application: + +==== .src/main/resources/application.properties ---- server.servlet.session.timeout=1m # Session timeout. If a duration suffix is not specified, seconds will be used. ---- ==== +===== -[NOTE] -==== -For the sample to work, you must https://redis.io/download[install Redis 2.8+] on localhost and run it with the default port (6379). +NOTE: For the sample to work, you must https://redis.io/download[install Redis 2.8+] on localhost and run it with the default port (6379). Alternatively, you can update the `RedisConnectionFactory` to point to a Redis server. -Another option is to use https://www.docker.com/[Docker] to run Redis on localhost. See https://hub.docker.com/_/redis/[Docker Redis repository] for detailed instructions. -==== - ----- -$ ./gradlew :spring-session-sample-boot-websocket:bootRun ----- +Another option is to use https://www.docker.com/[Docker] to run Redis on localhost. +See https://hub.docker.com/_/redis/[Docker Redis repository] for detailed instructions. You should now be able to access the application at http://localhost:8080/ -=== Exploring the websocket Sample Application +=== Exploring the `websocket` Sample Application -Try using the application. Authenticate with the following information: +Now you can try using the application. Authenticate with the following information: -* **Username** _rob_ -* **Password** _password_ +* *Username* _rob_ +* *Password* _password_ -Now click the **Login** button. You should now be authenticated as the user **rob**. +Now click the *Login* button. You should now be authenticated as the user **rob**. Open an incognito window and access http://localhost:8080/ -You will be prompted with a log in form. Authenticate with the following information: +You are prompted with a login form. Authenticate with the following information: -* **Username** _luke_ -* **Password** _password_ +* *Username* _luke_ +* *Password* _password_ -Now send a message from *rob* to *luke*. The message should appear. +Now send a message from rob to luke. The message should appear. -Wait for two minutes and try sending a message from *rob* to *luke* again. -You will see that the message is no longer sent. +Wait for two minutes and try sending a message from rob to luke again. +You can see that the message is no longer sent. [NOTE] .Why two minutes? ==== -Spring Session will expire in 60 seconds, but the notification from Redis is not guaranteed to happen within 60 seconds. +Spring Session expires in 60 seconds, but the notification from Redis is not guaranteed to happen within 60 seconds. To ensure the socket is closed in a reasonable amount of time, Spring Session runs a background task every minute at 00 seconds that forcibly cleans up any expired sessions. -This means you will need to wait at most two minutes before the WebSocket connection is terminated. +This means you need to wait at most two minutes before the WebSocket connection is terminated. ==== -Try accessing http://localhost:8080/ -You will be prompted to authenticate again. +You can now try accessing http://localhost:8080/ +You are prompted to authenticate again. This demonstrates that the session properly expires. -Now repeat the same exercise, but instead of waiting two minutes send a message from *each* of the users every 30 seconds. -You will see that the messages continue to be sent. +Now repeat the same exercise, but instead of waiting two minutes, send a message from each of the users every 30 seconds. +You can see that the messages continue to be sent. Try accessing http://localhost:8080/ -You will not be prompted to authenticate again. +You are not prompted to authenticate again. This demonstrates the session is kept alive. NOTE: Only messages sent from a user keep the session alive. This is because only messages coming from a user imply user activity. -Messages received do not imply activity and thus do not renew the session expiration. +Received messages do not imply activity and, thus, do not renew the session expiration. diff --git a/docs/src/docs/asciidoc/guides/grails3.adoc b/docs/src/docs/asciidoc/guides/grails3.adoc index 8639c117..967c0224 100644 --- a/docs/src/docs/asciidoc/guides/grails3.adoc +++ b/docs/src/docs/asciidoc/guides/grails3.adoc @@ -2,17 +2,19 @@ Eric Helgeson :toc: -This guide describes how to use Spring Session to transparently leverage Redis to back a web application's `HttpSession` when using Grails 3.1 +This guide describes how to use Spring Session to transparently leverage Redis to back a web application's `HttpSession` when you use Grails 3.1 -NOTE: Grails 3.1 is based off spring boot 1.3 so much of the advanced configuration and options can be found in the boot docs as well. +NOTE: Grails 3.1 is based off spring boot 1.3, so much of the advanced configuration and options can be found in the Boot docs as well. -NOTE: The completed guide can be found in the <>. +NOTE: You can find the completed guid in the <>. == Updating Dependencies -Before you use Spring Session, you must ensure to update your dependencies. -We assume you are working with a working Grails 3.1 web profile. -Add the following dependencies: +Before you use Spring Session, you must update your dependencies. +We assume you are working with a working Grails 3.1 web profile. +You must add the following dependencies: + +==== .build.gradle [source,groovy] [subs="verbatim,attributes"] @@ -22,11 +24,13 @@ dependencies { compile 'org.springframework.session:spring-session:{spring-session-version}' } ---- +==== ifeval::["{version-snapshot}" == "true"] -Since We are using a SNAPSHOT version, we need to ensure to add the Spring Snapshot Maven Repository. -Ensure you have the following in your pom.xml: +Since we use a SNAPSHOT version, we need to ensure to add the Spring Snapshot Maven Repository. +You must have the following in your build.gradle: +==== .build.gradle [source,groovy] ---- @@ -36,12 +40,14 @@ repositories { } } ---- +==== endif::[] ifeval::["{version-milestone}" == "true"] -Since We are using a Milestone version, we need to ensure to add the Spring Milestone Maven Repository. -Ensure you have the following in your pom.xml: +Since we use a Milestone version, we need to add the Spring Milestone Maven Repository. +You must have the following in your build.gradle: +==== .build.gradle [source,groovy] ---- @@ -51,6 +57,7 @@ repositories { } } ---- +==== endif::[] [[grails3-redis-configuration]] @@ -58,8 +65,9 @@ endif::[] Spring Boot automatically creates a `RedisConnectionFactory` that connects Spring Session to a Redis Server on localhost on port 6379 (default port). In a production environment you need to ensure to update your configuration to point to your Redis server. -For example, you can include the following in your *application.yml* +For example, you can include the following in your application.yml: +==== .grails-app/conf/application.yml [source,yml] ---- @@ -69,8 +77,9 @@ spring: password: secret port: 6397 ---- +==== -For more information, refer to https://docs.spring.io/spring-boot/docs/{spring-boot-version}/reference/htmlsingle/#boot-features-connecting-to-redis[Connecting to Redis] portion of the Spring Boot documentation. +For more information, see the https://docs.spring.io/spring-boot/docs/{spring-boot-version}/reference/htmlsingle/#boot-features-connecting-to-redis[Connecting to Redis] portion of the Spring Boot documentation. [[grails3-sample]] == Grails 3 Sample Application @@ -82,52 +91,61 @@ The Grails 3 Sample Application demonstrates how to use Spring Session to transp You can run the sample by obtaining the {download-url}[source code] and invoking the following command: -[NOTE] -==== -For the sample to work, you must https://redis.io/download[install Redis 2.8+] on localhost and run it with the default port (6379). -Alternatively, you can update the `RedisConnectionFactory` to point to a Redis server. -Another option is to use https://www.docker.com/[Docker] to run Redis on localhost. See https://hub.docker.com/_/redis/[Docker Redis repository] for detailed instructions. -==== - ---- $ ./gradlew :spring-session-sample-misc-grails3:bootRun ---- +NOTE:For the sample to work, you must https://redis.io/download[install Redis 2.8+] on localhost and run it with the default port (6379). +Alternatively, you can update the `RedisConnectionFactory` to point to a Redis server. +Another option is to use https://www.docker.com/[Docker] to run Redis on localhost. +See https://hub.docker.com/_/redis/[Docker Redis repository] for detailed instructions. + You should now be able to access the application at http://localhost:8080/test/index [[grails3-explore]] -=== Exploring the security Sample Application +=== Exploring the `security` Sample Application -Try using the application. Enter the following to log in: +You can now try using the application. Enter the following to log in: -* **Username** _user_ -* **Password** _password_ +* *Username* _user_ +* *Password* _password_ -Now click the **Login** button. -You should now see a message indicating your are logged in with the user entered previously. +Now click the *Login* button. +You should now see a message indicating that your are logged in with the user entered previously. The user's information is stored in Redis rather than Tomcat's `HttpSession` implementation. [[grails3-how]] -=== How does it work? +=== How Does It Work? -Instead of using Tomcat's `HttpSession`, we are actually persisting the values in Redis. +Instead of using Tomcat's `HttpSession`, we persist the values in Redis. Spring Session replaces the `HttpSession` with an implementation that is backed by Redis. -When Spring Security's `SecurityContextPersistenceFilter` saves the `SecurityContext` to the `HttpSession` it is then persisted into Redis. +When Spring Security's `SecurityContextPersistenceFilter` saves the `SecurityContext` to the `HttpSession`, it is then persisted into Redis. -When a new `HttpSession` is created, Spring Session creates a cookie named SESSION in your browser that contains the id of your session. -Go ahead and view the cookies (click for help with https://developers.google.com/web/tools/chrome-devtools/manage-data/cookies[Chrome] or https://developer.mozilla.org/en-US/docs/Tools/Storage_Inspector[Firefox]). +When a new `HttpSession` is created, Spring Session creates a cookie named `SESSION` in your browser. +That cookie contains the ID of your session. +You can view the cookies (with https://developers.google.com/web/tools/chrome-devtools/manage-data/cookies[Chrome] or https://developer.mozilla.org/en-US/docs/Tools/Storage_Inspector[Firefox]). -If you like, you can easily remove the session using redis-cli. For example, on a Linux based system you can type: +You can remove the session by using redis-cli. +For example, on a Linux based system you can type the following: +==== +---- $ redis-cli keys '*' | xargs redis-cli del +---- +==== TIP: The Redis documentation has instructions for https://redis.io/topics/quickstart[installing redis-cli]. -Alternatively, you can also delete the explicit key. Enter the following into your terminal ensuring to replace `7e8383a4-082c-4ffe-a4bc-c40fd3363c5e` with the value of your SESSION cookie: +Alternatively, you can also delete the explicit key. +To do so, enter the following into your terminal, being sure to replace `7e8383a4-082c-4ffe-a4bc-c40fd3363c5e` with the value of your `SESSION` cookie: +==== +---- $ redis-cli del spring:session:sessions:7e8383a4-082c-4ffe-a4bc-c40fd3363c5e +---- +==== -Now visit the application at http://localhost:8080/test/index and observe that we are no longer authenticated. +Now you can visit the application at http://localhost:8080/test/index and see that we are no longer authenticated. -NOTE: Spring Session will not work with grails flash scope without additional work. + -See this answer for an explanation: https://stackoverflow.com/a/43311427 +NOTE: Spring Session does not work with Grails flash scope without additional work. +See https://stackoverflow.com/a/43311427 for an explanation. diff --git a/docs/src/docs/asciidoc/guides/java-custom-cookie.adoc b/docs/src/docs/asciidoc/guides/java-custom-cookie.adoc index 823d672d..316e8f8e 100644 --- a/docs/src/docs/asciidoc/guides/java-custom-cookie.adoc +++ b/docs/src/docs/asciidoc/guides/java-custom-cookie.adoc @@ -3,100 +3,95 @@ Rob Winch :toc: This guide describes how to configure Spring Session to use custom cookies with Java Configuration. -The guide assumes you have already link:./httpsession.html[setup Spring Session in your project]. +The guide assumes you have already link:./httpsession.html[set up Spring Session in your project]. -NOTE: The completed guide can be found in the <>. +NOTE: You can find the completed guide in the <>. [[custom-cookie-spring-configuration]] == Spring Java Configuration -Once you have setup Spring Session you can easily customize how the session cookie is written by exposing a `CookieSerializer` as a Spring Bean. -Out of the box, Spring Session comes with `DefaultCookieSerializer`. -Simply exposing the `DefaultCookieSerializer` as a Spring Bean will augment the existing configuration when using configurations like `@EnableRedisHttpSession`. -You can find an example of customizing Spring Session's cookie below: +Once you have set up Spring Session, you can customize how the session cookie is written by exposing a `CookieSerializer` as a Spring bean. +Spring Session comes with `DefaultCookieSerializer`. +Exposing the `DefaultCookieSerializer` as a Spring bean augments the existing configuration when you use configurations like `@EnableRedisHttpSession`. +The following example shows how to customize Spring Session's cookie: +==== [source,java] ---- include::{samples-dir}javaconfig/custom-cookie/src/main/java/sample/Config.java[tags=cookie-serializer] ---- -<1> We customize the name of the cookie to be JSESSIONID -<2> We customize the path of the cookie to be "/" (rather than the default of the context root) -<3> We customize the domain name pattern (a regular expression) to be `^.+?\\.(\\w+\\.[a-z]+)$` +<1> We customize the name of the cookie to be `JSESSIONID`. +<2> We customize the path of the cookie to be `/` (rather than the default of the context root). +<3> We customize the domain name pattern (a regular expression) to be `^.+?\\.(\\w+\\.[a-z]+)$`. This allows sharing a session across domains and applications. -If the regular expression does not match, no domain is set and the existing domain will be used. -If the regular expression matches, the first https://docs.oracle.com/javase/tutorial/essential/regex/groups.html[grouping] will be used as the domain. -This means that a request to https://child.example.com will set the domain to example.com. -However, a request to http://localhost:8080/ or http://192.168.1.100:8080/ will leave the cookie unset and thus still work in development without any changes necessary for production. +If the regular expression does not match, no domain is set and the existing domain is used. +If the regular expression matches, the first https://docs.oracle.com/javase/tutorial/essential/regex/groups.html[grouping] is used as the domain. +This means that a request to https://child.example.com sets the domain to `example.com`. +However, a request to http://localhost:8080/ or http://192.168.1.100:8080/ leaves the cookie unset and, thus, still works in development without any changes being necessary for production. +==== -[WARNING] -==== -It is important to note that users should only match on valid domain characters since the domain name is reflected in the response. -This is prevent a malicious user from performing attacks like https://en.wikipedia.org/wiki/HTTP_response_splitting[HTTP Response Splitting]. -==== +WARNING: You should only match on valid domain characters, since the domain name is reflected in the response. +Doing so prevents a malicious user from performing such attacks as https://en.wikipedia.org/wiki/HTTP_response_splitting[HTTP Response Splitting]. [[custom-cookie-options]] == Configuration Options -The configuration options available are: +The following configuration options are available: -* `cookieName` - the name of the cookie to use -Default "SESSION" -* `useSecureCookie` - specify if a secure cookie be used -Default use value of `HttpServletRequest.isSecure()` at the time of creation. -* `cookiePath` - the path of the cookie -Default is context root -* `cookieMaxAge` - specifies the max age of the cookie to be set at the time the session is created. -Default is -1 which indicates the cookie will be removed when the browser is closed. -* `jvmRoute` - specifies a suffix to be appended to the session id and included in the cookie. +* `cookieName`: The name of the cookie to use. +Default: `SESSION`. +* `useSecureCookie`: Specifies whether a secure cookie should be used. +Default: Use the value of `HttpServletRequest.isSecure()` at the time of creation. +* `cookiePath`: The path of the cookie. +Default: The context root. +* `cookieMaxAge`: Specifies the max age of the cookie to be set at the time the session is created. +Default: `-1`, which indicates the cookie should be removed when the browser is closed. +* `jvmRoute`: Specifies a suffix to be appended to the session ID and included in the cookie. Used to identify which JVM to route to for session affinity. -With some implementations (i.e. Redis) this provides no performance benefit. -However, this can help with tracing logs of a particular user. -* `domainName` - allows specifying a specific domain name to be used for the cookie. -This option is simple to understand, but will likely require a different configuration between development and production environments. -See domainNamePattern as an alternative. -* `domainNamePattern` - a case insensitive pattern used to extract the domain name from the `HttpServletRequest#getServerName()`. -The pattern should provide a single grouping used to extract the value of the cookie domain. -If the regular expression does not match, no domain is set and the existing domain will be used. -If the regular expression matches, the first https://docs.oracle.com/javase/tutorial/essential/regex/groups.html[grouping] will be used as the domain. +With some implementations (that is, Redis) this option provides no performance benefit. +However, it can help with tracing logs of a particular user. +* `domainName`: Allows specifying a specific domain name to be used for the cookie. +This option is simple to understand but often requires a different configuration between development and production environments. +See `domainNamePattern` as an alternative. +* `domainNamePattern`: A case-insensitive pattern used to extract the domain name from the `HttpServletRequest#getServerName()`. +The pattern should provide a single grouping that is used to extract the value of the cookie domain. +If the regular expression does not match, no domain is set and the existing domain is used. +If the regular expression matches, the first https://docs.oracle.com/javase/tutorial/essential/regex/groups.html[grouping] is used as the domain. -[WARNING] -==== -It is important to note that users should only match on valid domain characters since the domain name is reflected in the response. -This is prevent a malicious user from performing attacks like https://en.wikipedia.org/wiki/HTTP_response_splitting[HTTP Response Splitting]. -==== +WARNING: You should only match on valid domain characters, since the domain name is reflected in the response. +Doing so prevents a malicious user from performing such attacks as https://en.wikipedia.org/wiki/HTTP_response_splitting[HTTP Response Splitting]. [[custom-cookie-sample]] -== custom-cookie Sample Application +== `custom-cookie` Sample Application +This section describes how to work with the `custom-cookie` sample application. - -=== Running the custom-cookie Sample Application +=== Running the `custom-cookie` Sample Application You can run the sample by obtaining the {download-url}[source code] and invoking the following command: -[NOTE] ==== -For the sample to work, you must https://redis.io/download[install Redis 2.8+] on localhost and run it with the default port (6379). -Alternatively, you can update the `RedisConnectionFactory` to point to a Redis server. -Another option is to use https://www.docker.com/[Docker] to run Redis on localhost. See https://hub.docker.com/_/redis/[Docker Redis repository] for detailed instructions. -==== - ---- $ ./gradlew :spring-session-sample-javaconfig-custom-cookie:tomcatRun ---- +==== + +NOTE: For the sample to work, you must https://redis.io/download[install Redis 2.8+] on localhost and run it with the default port (6379). +Alternatively, you can update the `RedisConnectionFactory` to point to a Redis server. +Another option is to use https://www.docker.com/[Docker] to run Redis on localhost. See https://hub.docker.com/_/redis/[Docker Redis repository] for detailed instructions. You should now be able to access the application at http://localhost:8080/ -=== Exploring the custom-cookie Sample Application +=== Exploring the `custom-cookie` Sample Application -Try using the application. Fill out the form with the following information: +Now you can use the application. Fill out the form with the following information: -* **Attribute Name:** _username_ -* **Attribute Value:** _rob_ +* *Attribute Name:* _username_ +* *Attribute Value:* _rob_ -Now click the **Set Attribute** button. +Now click the *Set Attribute* button. You should now see the values displayed in the table. -If you look at the cookies for the application, you can see the cookie is saved to the custom name of JSESSIONID +If you look at the cookies for the application, you can see the cookie is saved to the custom name of `JSESSIONID`. diff --git a/docs/src/docs/asciidoc/guides/java-hazelcast.adoc b/docs/src/docs/asciidoc/guides/java-hazelcast.adoc index 89b56392..7f152244 100644 --- a/docs/src/docs/asciidoc/guides/java-hazelcast.adoc +++ b/docs/src/docs/asciidoc/guides/java-hazelcast.adoc @@ -2,15 +2,17 @@ Tommy Ludwig; Rob Winch :toc: -This guide describes how to use Spring Session along with Spring Security using Hazelcast as your data store. -It assumes you have already applied Spring Security to your application. +This guide describes how to use Spring Session along with Spring Security when you use Hazelcast as your data store. +It assumes that you have already applied Spring Security to your application. -NOTE: The completed guide can be found in the <>. +NOTE: You cand find the completed guide in the <>. == Updating Dependencies -Before you use Spring Session, you must ensure to update your dependencies. -If you are using Maven, ensure to add the following dependencies: +Before you use Spring Session, you must update your dependencies. +If you use Maven, you must add the following dependencies: + +==== .pom.xml [source,xml] [subs="verbatim,attributes"] @@ -30,11 +32,13 @@ If you are using Maven, ensure to add the following dependencies: ---- +==== ifeval::["{version-snapshot}" == "true"] -Since We are using a SNAPSHOT version, we need to ensure to add the Spring Snapshot Maven Repository. -Ensure you have the following in your pom.xml: +Since we are using a SNAPSHOT version, we need to add the Spring Snapshot Maven Repository. +You must have the following in your pom.xml: +==== .pom.xml [source,xml] ---- @@ -48,12 +52,14 @@ Ensure you have the following in your pom.xml: ---- +==== endif::[] ifeval::["{version-milestone}" == "true"] -Since We are using a Milestone version, we need to ensure to add the Spring Milestone Maven Repository. -Ensure you have the following in your pom.xml: +Since we are using a Milestone version, we need to add the Spring Milestone Maven Repository. +You must have the following in your pom.xml: +==== .pom.xml [source,xml] ---- @@ -62,6 +68,7 @@ Ensure you have the following in your pom.xml: https://repo.spring.io/libs-milestone ---- +==== endif::[] // tag::config[] @@ -70,126 +77,146 @@ endif::[] == Spring Configuration After adding the required dependencies, we can create our Spring configuration. -The Spring configuration is responsible for creating a Servlet Filter that replaces the `HttpSession` implementation with an implementation backed by Spring Session. -Add the following Spring Configuration: +The Spring configuration is responsible for creating a servlet filter that replaces the `HttpSession` implementation with an implementation backed by Spring Session. +To do so, add the following Spring Configuration: +==== [source,java] ---- include::{docs-test-dir}docs/http/HazelcastHttpSessionConfig.java[tags=config] ---- -<1> The `@EnableHazelcastHttpSession` annotation creates a Spring Bean with the name of `springSessionRepositoryFilter` that implements Filter. -The filter is what is in charge of replacing the `HttpSession` implementation to be backed by Spring Session. -In this instance Spring Session is backed by Hazelcast. -<2> In order to support retrieval of sessions by principal name index, appropriate `ValueExtractor` needs to be registered. +<1> The `@EnableHazelcastHttpSession` annotation creates a Spring bean named `springSessionRepositoryFilter` that implements `Filter`. +The filter is in charge of replacing the `HttpSession` implementation to be backed by Spring Session. +In this instance, Spring Session is backed by Hazelcast. +<2> In order to support retrieval of sessions by principal name index, an appropriate `ValueExtractor` needs to be registered. Spring Session provides `PrincipalNameExtractor` for this purpose. <3> We create a `HazelcastInstance` that connects Spring Session to Hazelcast. -By default, an embedded instance of Hazelcast is started and connected to by the application. -For more information on configuring Hazelcast, refer to the http://docs.hazelcast.org/docs/{hazelcast-version}/manual/html-single/index.html#hazelcast-configuration[reference documentation]. +By default, the application starts and connects to an embedded instance of Hazelcast. +For more information on configuring Hazelcast, see the http://docs.hazelcast.org/docs/{hazelcast-version}/manual/html-single/index.html#hazelcast-configuration[reference documentation]. +==== == Servlet Container Initialization -Our <> created a Spring Bean named `springSessionRepositoryFilter` that implements `Filter`. +Our <> 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. -Since our application is already loading Spring configuration using our `SecurityInitializer` class, we can simply add our `SessionConfig` class to it. +Since our application is already loading Spring configuration by using our `SecurityInitializer` class, we can add our `SessionConfig` class to it. +The following listing shows how to do so: +==== .src/main/java/sample/SecurityInitializer.java [source,java] ---- include::{samples-dir}javaconfig/hazelcast/src/main/java/sample/SecurityInitializer.java[tags=class] ---- +==== -Last we need to ensure that our Servlet Container (i.e. Tomcat) uses our `springSessionRepositoryFilter` for every request. +Last, we need to ensure that our Servlet Container (that is, Tomcat) uses our `springSessionRepositoryFilter` for every request. It is extremely important that Spring Session's `springSessionRepositoryFilter` is invoked before Spring Security's `springSecurityFilterChain`. -This ensures that the `HttpSession` that Spring Security uses is backed by Spring Session. -Fortunately, Spring Session provides a utility class named `AbstractHttpSessionApplicationInitializer` that makes this extremely easy. -You can find an example below: +Doing so ensures that the `HttpSession` that Spring Security uses is backed by Spring Session. +Fortunately, Spring Session provides a utility class named `AbstractHttpSessionApplicationInitializer` that makes this doing so easy. +The following example shows how to do so: +==== .src/main/java/sample/Initializer.java [source,java] ---- include::{samples-dir}javaconfig/hazelcast/src/main/java/sample/Initializer.java[tags=class] ---- +==== -NOTE: The name of our class (Initializer) does not matter. What is important is that we extend `AbstractHttpSessionApplicationInitializer`. +NOTE: The name of our class (`Initializer`) does not matter. What is important is that we extend `AbstractHttpSessionApplicationInitializer`. -By extending `AbstractHttpSessionApplicationInitializer` we ensure that the Spring Bean by the name `springSessionRepositoryFilter` is registered with our Servlet Container for every request before Spring Security's `springSecurityFilterChain`. +By extending `AbstractHttpSessionApplicationInitializer`, we ensure that the Spring Bean named `springSessionRepositoryFilter` is registered with our servlet container for every request before Spring Security's `springSecurityFilterChain`. // end::config[] [[hazelcast-spring-security-sample]] == Hazelcast Spring Security Sample Application +This section describes how to work with the Hazelcast Spring Security sample application. + === Running the Sample Application You can run the sample by obtaining the {download-url}[source code] and invoking the following command: -[NOTE] ==== -Hazelcast will run in embedded mode with your application by default, but if you want to connect -to a stand alone instance instead, you can configure it by following the instructions in the -http://docs.hazelcast.org/docs/{hazelcast-version}/manual/html-single/index.html#hazelcast-configuration[reference documentation]. -==== - ---- $ ./gradlew :spring-session-sample-javaconfig-hazelcast:tomcatRun ---- +==== + +NOTE: By default, Hazelcast runs in embedded mode with your application. +However, if you want to connect to a standalone instance instead, you can configure it by following the instructions in the http://docs.hazelcast.org/docs/{hazelcast-version}/manual/html-single/index.html#hazelcast-configuration[reference documentation]. You should now be able to access the application at http://localhost:8080/ -=== Exploring the security Sample Application +=== Exploring the Security Sample Application -Try using the application. Enter the following to log in: +You can now try using the application. +To do so, enter the following to log in: -* **Username** _user_ -* **Password** _password_ +* *Username* _user_ +* *Password* _password_ -Now click the **Login** button. -You should now see a message indicating your are logged in with the user entered previously. +Now click the *Login* button. +You should now see a message indicating that your are logged in with the user entered previously. The user's information is stored in Hazelcast rather than Tomcat's `HttpSession` implementation. -=== How does it work? +=== How Does It Work? -Instead of using Tomcat's `HttpSession`, we are actually persisting the values in Hazelcast. +Instead of using Tomcat's `HttpSession`, we persist the values in Hazelcast. Spring Session replaces the `HttpSession` with an implementation that is backed by a `Map` in Hazelcast. -When Spring Security's `SecurityContextPersistenceFilter` saves the `SecurityContext` to the `HttpSession` it is then persisted into Hazelcast. +When Spring Security's `SecurityContextPersistenceFilter` saves the `SecurityContext` to the `HttpSession`, it is then persisted into Hazelcast. -When a new `HttpSession` is created, Spring Session creates a cookie named SESSION in your browser that contains the id of your session. -Go ahead and view the cookies (click for help with https://developers.google.com/web/tools/chrome-devtools/manage-data/cookies[Chrome] or https://developer.mozilla.org/en-US/docs/Tools/Storage_Inspector[Firefox]). +When a new `HttpSession` is created, Spring Session creates a cookie named `SESSION` in your browser. That cookie contains the ID of your session. +You can view the cookies (with https://developers.google.com/web/tools/chrome-devtools/manage-data/cookies[Chrome] or https://developer.mozilla.org/en-US/docs/Tools/Storage_Inspector[Firefox]). -=== Interact with the data store +=== Interacting with the Data Store -If you like, you can remove the session using http://docs.hazelcast.org/docs/{hazelcast-version}/manual/html-single/index.html#hazelcast-java-client[a Java client], +You can remove the session by using http://docs.hazelcast.org/docs/{hazelcast-version}/manual/html-single/index.html#hazelcast-java-client[a Java client], http://docs.hazelcast.org/docs/{hazelcast-version}/manual/html-single/index.html#other-client-implementations[one of the other clients], or the http://docs.hazelcast.org/docs/{hazelcast-version}/manual/html-single/index.html#management-center[management center]. -==== Using the console +==== Using the Console -For example, using the management center console after connecting to your Hazelcast node: +For example, to remove the session by using the management center console after connecting to your Hazelcast node, run the following commands: +==== +---- default> ns spring:session:sessions spring:session:sessions> m.clear +---- +==== TIP: The Hazelcast documentation has instructions for http://docs.hazelcast.org/docs/{hazelcast-version}/manual/html-single/index.html#executing-console-commands[the console]. -Alternatively, you can also delete the explicit key. Enter the following into the console ensuring to replace `7e8383a4-082c-4ffe-a4bc-c40fd3363c5e` with the value of your SESSION cookie: +Alternatively, you can also delete the explicit key. Enter the following into the console, being sure to replace `7e8383a4-082c-4ffe-a4bc-c40fd3363c5e` with the value of your `SESSION` cookie: +==== +---- spring:session:sessions> m.remove 7e8383a4-082c-4ffe-a4bc-c40fd3363c5e +---- +==== Now visit the application at http://localhost:8080/ and observe that we are no longer authenticated. ==== Using the REST API -As described in the other clients section of the documentation, there is a +As described in the section of the documentation that cover other clients, there is a http://docs.hazelcast.org/docs/{hazelcast-version}/manual/html-single/index.html#rest-client[REST API] provided by the Hazelcast node(s). -For example, you could delete an individual key as follows (replacing `7e8383a4-082c-4ffe-a4bc-c40fd3363c5e` with the value of your SESSION cookie): +For example, you could delete an individual key as follows (being sure to replace `7e8383a4-082c-4ffe-a4bc-c40fd3363c5e` with the value of your SESSION cookie): +==== +---- $ curl -v -X DELETE http://localhost:xxxxx/hazelcast/rest/maps/spring:session:sessions/7e8383a4-082c-4ffe-a4bc-c40fd3363c5e +---- +==== -TIP: The port number of the Hazelcast node will be printed to the console on startup. Replace `xxxxx` above with the port number. +TIP: The port number of the Hazelcast node is printed to the console on startup. Replace `xxxxx` with the port number. -Now observe that you are no longer authenticated with this session. +Now you can see that you are no longer authenticated with this session. diff --git a/docs/src/docs/asciidoc/guides/java-jdbc.adoc b/docs/src/docs/asciidoc/guides/java-jdbc.adoc index cb92a5df..d642ad2c 100644 --- a/docs/src/docs/asciidoc/guides/java-jdbc.adoc +++ b/docs/src/docs/asciidoc/guides/java-jdbc.adoc @@ -4,12 +4,14 @@ Rob Winch, Vedran Pavić This guide describes how to use Spring Session to transparently leverage a relational database to back a web application's `HttpSession` with Java Configuration. -NOTE: The completed guide can be found in the <>. +NOTE: You can find the completed guide in the <>. == Updating Dependencies -Before you use Spring Session, you must ensure to update your dependencies. -If you are using Maven, ensure to add the following dependencies: +Before you use Spring Session, you must update your dependencies. +If you use Maven, you must add the following dependencies: + +==== .pom.xml [source,xml] [subs="verbatim,attributes"] @@ -30,11 +32,13 @@ If you are using Maven, ensure to add the following dependencies: ---- +==== ifeval::["{version-snapshot}" == "true"] Since we are using a SNAPSHOT version, we need to ensure to add the Spring Snapshot Maven Repository. -Ensure you have the following in your pom.xml: +You must have the following in your pom.xml: +==== .pom.xml [source,xml] ---- @@ -48,12 +52,14 @@ Ensure you have the following in your pom.xml: ---- +==== endif::[] ifeval::["{version-milestone}" == "true"] -Since We are using a Milestone version, we need to ensure to add the Spring Milestone Maven Repository. -Ensure you have the following in your pom.xml: +Since we are using a Milestone version, we need to add the Spring Milestone Maven Repository. +You must have the following in your pom.xml: +==== .pom.xml [source,xml] ---- @@ -62,6 +68,7 @@ Ensure you have the following in your pom.xml: https://repo.spring.io/libs-milestone ---- +==== endif::[] // tag::config[] @@ -71,82 +78,95 @@ endif::[] After adding the required dependencies, we can create our Spring configuration. The Spring configuration is responsible for creating a Servlet Filter that replaces the `HttpSession` implementation with an implementation backed by Spring Session. -Add the following Spring Configuration: +To do so, add the following Spring Configuration: +==== [source,java] ---- include::{samples-dir}javaconfig/jdbc/src/main/java/sample/Config.java[tags=class] ---- -<1> The `@EnableJdbcHttpSession` annotation creates a Spring Bean with the name of `springSessionRepositoryFilter` that implements Filter. -The filter is what is in charge of replacing the `HttpSession` implementation to be backed by Spring Session. -In this instance Spring Session is backed by a relational database. -<2> We create a `dataSource` that connects Spring Session to an embedded instance of H2 database. -We configure the H2 database to create database tables using the SQL script which is included in Spring Session. +<1> The `@EnableJdbcHttpSession` annotation creates a Spring Bean with the name of `springSessionRepositoryFilter`. +That bean implements `Filter`. +The filter is in charge of replacing the `HttpSession` implementation to be backed by Spring Session. +In this instance, Spring Session is backed by a relational database. +<2> We create a `dataSource` that connects Spring Session to an embedded instance of an H2 database. +We configure the H2 database to create database tables by using the SQL script that is included in Spring Session. <3> We create a `transactionManager` that manages transactions for previously configured `dataSource`. +==== -For additional information on how to configure data access related concerns, please refer to the https://docs.spring.io/spring/docs/{spring-framework-version}/spring-framework-reference/data-access.html[Spring Framework Reference Documentation]. +For additional information on how to configure data access related concerns, see the https://docs.spring.io/spring/docs/{spring-framework-version}/spring-framework-reference/data-access.html[Spring Framework Reference Documentation]. == Java Servlet Container Initialization -Our <> created a Spring Bean named `springSessionRepositoryFilter` that implements `Filter`. +Our <> 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 `Config` class. -Last we need to ensure that our Servlet Container (i.e. Tomcat) uses our `springSessionRepositoryFilter` for every request. -Fortunately, Spring Session provides a utility class named `AbstractHttpSessionApplicationInitializer` both of these steps extremely easy. -You can find an example below: +Last, we need to ensure that our Servlet Container (that is, Tomcat) uses our `springSessionRepositoryFilter` for every request. +Fortunately, Spring Session provides a utility class named `AbstractHttpSessionApplicationInitializer` to make both of these steps easy. +The following example shows how to do so: +==== .src/main/java/sample/Initializer.java [source,java] ---- include::{samples-dir}javaconfig/jdbc/src/main/java/sample/Initializer.java[tags=class] ---- -NOTE: The name of our class (Initializer) does not matter. What is important is that we extend `AbstractHttpSessionApplicationInitializer`. +NOTE: The name of our class (Initializer) does not matter. +What is important is that we extend `AbstractHttpSessionApplicationInitializer`. <1> The first step is to extend `AbstractHttpSessionApplicationInitializer`. -This ensures that the Spring Bean by the name `springSessionRepositoryFilter` is registered with our Servlet Container for every request. -<2> `AbstractHttpSessionApplicationInitializer` also provides a mechanism to easily ensure Spring loads our `Config`. +Doing so ensures that the Spring bean named `springSessionRepositoryFilter` is registered with our Servlet Container for every request. +<2> `AbstractHttpSessionApplicationInitializer` also provides a mechanism to ensure Spring loads our `Config`. +==== // end::config[] [[httpsession-jdbc-sample]] -== httpsession-jdbc Sample Application +== `httpsession-jdbc` Sample Application -=== Running the httpsession-jdbc Sample Application +This section describes how to work with the `httpsession-jdbc` Sample Application. + +=== Running the `httpsession-jdbc` Sample Application You can run the sample by obtaining the {download-url}[source code] and invoking the following command: +==== ---- $ ./gradlew :spring-session-sample-javaconfig-jdbc:tomcatRun ---- +==== You should now be able to access the application at http://localhost:8080/ -=== Exploring the httpsession-jdbc Sample Application +=== Exploring the `httpsession-jdbc` Sample Application -Try using the application. Fill out the form with the following information: +Now you can try using the application. To do so, fill out the form with the following information: -* **Attribute Name:** _username_ -* **Attribute Value:** _rob_ +* *Attribute Name:* _username_ +* *Attribute Value:* _rob_ -Now click the **Set Attribute** button. You should now see the values displayed in the table. +Now click the *Set Attribute* button. You should now see the values displayed in the table. -=== How does it work? +=== How Does It Work? -We interact with the standard `HttpSession` in the `SessionServlet` shown below: +We interact with the standard `HttpSession` in the `SessionServlet` shown in the following listing: +==== .src/main/java/sample/SessionServlet.java [source,java] ---- include::{samples-dir}javaconfig/jdbc/src/main/java/sample/SessionServlet.java[tags=class] ---- +==== -Instead of using Tomcat's `HttpSession`, we are actually persisting the values in H2 database. -Spring Session creates a cookie named SESSION in your browser that contains the id of your session. -Go ahead and view the cookies (click for help with https://developers.google.com/web/tools/chrome-devtools/manage-data/cookies[Chrome] or https://developer.mozilla.org/en-US/docs/Tools/Storage_Inspector[Firefox]). +Instead of using Tomcat's `HttpSession`, we persist the values in H2 database. +Spring Session creates a cookie named `SESSION` in your browser. +That cookie contains the ID of your session. +You can view the cookies (with https://developers.google.com/web/tools/chrome-devtools/manage-data/cookies[Chrome] or https://developer.mozilla.org/en-US/docs/Tools/Storage_Inspector[Firefox]). -If you like, you can easily remove the session using H2 web console available at: http://localhost:8080/h2-console/ (use `jdbc:h2:mem:testdb` for JDBC URL) +If you like, you can remove the session by using the H2 web console available at: http://localhost:8080/h2-console/ (use `jdbc:h2:mem:testdb` for JDBC URL). -Now visit the application at http://localhost:8080/ and observe that the attribute we added is no longer displayed. +Now you can visit the application at http://localhost:8080/ and see that the attribute we added is no longer displayed. diff --git a/docs/src/docs/asciidoc/guides/java-redis.adoc b/docs/src/docs/asciidoc/guides/java-redis.adoc index f13d3f6f..b3255170 100644 --- a/docs/src/docs/asciidoc/guides/java-redis.adoc +++ b/docs/src/docs/asciidoc/guides/java-redis.adoc @@ -1,15 +1,17 @@ = Spring Session - HttpSession (Quick Start) Rob Winch :toc: +:version-snapshot: true This guide describes how to use Spring Session to transparently leverage Redis to back a web application's `HttpSession` with Java Configuration. -NOTE: The completed guide can be found in the <>. +NOTE: You can find the completed guide in the <>. == Updating Dependencies -Before you use Spring Session, you must ensure to update your dependencies. -If you are using Maven, ensure to add the following dependencies: +Before you use Spring Session, you must update your dependencies. +If you are using Maven, you must add the following dependencies: +==== .pom.xml [source,xml] [subs="verbatim,attributes"] @@ -35,11 +37,13 @@ If you are using Maven, ensure to add the following dependencies: ---- +==== ifeval::["{version-snapshot}" == "true"] Since we are using a SNAPSHOT version, we need to ensure to add the Spring Snapshot Maven Repository. -Ensure you have the following in your pom.xml: +You must have the following in your pom.xml: +==== .pom.xml [source,xml] ---- @@ -53,12 +57,14 @@ Ensure you have the following in your pom.xml: ---- +==== endif::[] ifeval::["{version-milestone}" == "true"] -Since We are using a Milestone version, we need to ensure to add the Spring Milestone Maven Repository. -Ensure you have the following in your pom.xml: +Since we are using a Milestone version, we need to ensure to add the Spring Milestone Maven Repository. +You must have the following in your pom.xml: +==== .pom.xml [source,xml] ---- @@ -67,6 +73,7 @@ Ensure you have the following in your pom.xml: https://repo.spring.io/libs-milestone ---- +==== endif::[] // tag::config[] @@ -75,20 +82,22 @@ endif::[] == Spring Java Configuration After adding the required dependencies, we can create our Spring configuration. -The Spring configuration is responsible for creating a Servlet Filter that replaces the `HttpSession` implementation with an implementation backed by Spring Session. -Add the following Spring Configuration: +The Spring configuration is responsible for creating a servlet filter that replaces the `HttpSession` implementation with an implementation backed by Spring Session. +To do so, add the following Spring Configuration: +==== [source,java] ---- include::{samples-dir}javaconfig/redis/src/main/java/sample/Config.java[tags=class] ---- -<1> The `@EnableRedisHttpSession` annotation creates a Spring Bean with the name of `springSessionRepositoryFilter` that implements Filter. -The filter is what is in charge of replacing the `HttpSession` implementation to be backed by Spring Session. -In this instance Spring Session is backed by Redis. +<1> The `@EnableRedisHttpSession` annotation creates a Spring Bean with the name of `springSessionRepositoryFilter` that implements `Filter`. +The filter is in charge of replacing the `HttpSession` 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, refer to the https://docs.spring.io/spring-data/data-redis/docs/{spring-data-redis-version}/reference/html/[reference documentation]. +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]. +==== == Java Servlet Container Initialization @@ -96,22 +105,24 @@ Our <> created a Spring B 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 `Config` class. -Last we need to ensure that our Servlet Container (i.e. Tomcat) uses our `springSessionRepositoryFilter` for every request. -Fortunately, Spring Session provides a utility class named `AbstractHttpSessionApplicationInitializer` both of these steps extremely easy. -You can find an example below: +Last, we need to ensure that our Servlet Container (that is, Tomcat) uses our `springSessionRepositoryFilter` for every request. +Fortunately, Spring Session provides a utility class named `AbstractHttpSessionApplicationInitializer` to make both of these steps easy. +The following shows an example: +==== .src/main/java/sample/Initializer.java [source,java] ---- include::{samples-dir}javaconfig/redis/src/main/java/sample/Initializer.java[tags=class] ---- -NOTE: The name of our class (Initializer) does not matter. What is important is that we extend `AbstractHttpSessionApplicationInitializer`. + +NOTE: The name of our class (`Initializer`) does not matter. What is important is that we extend `AbstractHttpSessionApplicationInitializer`. <1> The first step is to extend `AbstractHttpSessionApplicationInitializer`. -This ensures that the Spring Bean by the name `springSessionRepositoryFilter` is registered with our Servlet Container for every request. -<2> `AbstractHttpSessionApplicationInitializer` also provides a mechanism to easily ensure Spring loads our `Config`. - +Doing so ensures that the Spring Bean by the name of `springSessionRepositoryFilter` is registered with our Servlet Container for every request. +<2> `AbstractHttpSessionApplicationInitializer` also provides a mechanism to ensure Spring loads our `Config`. +==== // end::config[] [[httpsession-sample]] @@ -119,54 +130,66 @@ This ensures that the Spring Bean by the name `springSessionRepositoryFilter` is -=== Running the httpsession Sample Application +=== Running the `httpsession` Sample Application You can run the sample by obtaining the {download-url}[source code] and invoking the following command: -[NOTE] ==== -For the sample to work, you must https://redis.io/download[install Redis 2.8+] on localhost and run it with the default port (6379). -Alternatively, you can update the `RedisConnectionFactory` to point to a Redis server. -Another option is to use https://www.docker.com/[Docker] to run Redis on localhost. See https://hub.docker.com/_/redis/[Docker Redis repository] for detailed instructions. -==== - ---- $ ./gradlew :spring-session-sample-javaconfig-redis:tomcatRun ---- +==== + +NOTE: For the sample to work, you must https://redis.io/download[install Redis 2.8+] on localhost and run it with the default port (6379). +Alternatively, you can update the `RedisConnectionFactory` to point to a Redis server. +Another option is to use https://www.docker.com/[Docker] to run Redis on localhost. +See https://hub.docker.com/_/redis/[Docker Redis repository] for detailed instructions. You should now be able to access the application at http://localhost:8080/ -=== Exploring the httpsession Sample Application +=== Exploring the `httpsession` Sample Application -Try using the application. Fill out the form with the following information: +Now you can try to use the application. To do so, fill out the form with the following information: -* **Attribute Name:** _username_ -* **Attribute Value:** _rob_ +* *Attribute Name:* _username_ +* *Attribute Value:* _rob_ -Now click the **Set Attribute** button. You should now see the values displayed in the table. +Now click the *Set Attribute* button. You should now see the values displayed in the table. -=== How does it work? +=== How Does It Work? -We interact with the standard `HttpSession` in the `SessionServlet` shown below: +We interact with the standard `HttpSession` in the `SessionServlet` shown in the following listing: +==== .src/main/java/sample/SessionServlet.java [source,java] ---- include::{samples-dir}javaconfig/redis/src/main/java/sample/SessionServlet.java[tags=class] ---- +==== -Instead of using Tomcat's `HttpSession`, we are actually persisting the values in Redis. -Spring Session creates a cookie named SESSION in your browser that contains the id of your session. -Go ahead and view the cookies (click for help with https://developers.google.com/web/tools/chrome-devtools/manage-data/cookies[Chrome] or https://developer.mozilla.org/en-US/docs/Tools/Storage_Inspector[Firefox]). +Instead of using Tomcat's `HttpSession`, we persist the values in Redis. +Spring Session creates a cookie named `SESSION` in your browser. +That cookie contains the ID of your session. +You can view the cookies (with https://developers.google.com/web/tools/chrome-devtools/manage-data/cookies[Chrome] or https://developer.mozilla.org/en-US/docs/Tools/Storage_Inspector[Firefox]). -If you like, you can easily remove the session using redis-cli. For example, on a Linux based system you can type: +You can remove the session by using redis-cli. +For example, on a Linux based system you can type the following: +==== +---- $ redis-cli keys '*' | xargs redis-cli del +---- +==== TIP: The Redis documentation has instructions for https://redis.io/topics/quickstart[installing redis-cli]. -Alternatively, you can also delete the explicit key. Enter the following into your terminal ensuring to replace `7e8383a4-082c-4ffe-a4bc-c40fd3363c5e` with the value of your SESSION cookie: +Alternatively, you can also delete the explicit key. Enter the following into your terminal, being sure to replace `7e8383a4-082c-4ffe-a4bc-c40fd3363c5e` with the value of your SESSION cookie: +==== +---- $ redis-cli del spring:session:sessions:7e8383a4-082c-4ffe-a4bc-c40fd3363c5e +---- +==== -Now visit the application at http://localhost:8080/ and observe that the attribute we added is no longer displayed. +Now you can visit the application at http://localhost:8080/ and see that the attribute we added is no longer displayed. diff --git a/docs/src/docs/asciidoc/guides/java-rest.adoc b/docs/src/docs/asciidoc/guides/java-rest.adoc index ad3b978f..c0bfdae5 100644 --- a/docs/src/docs/asciidoc/guides/java-rest.adoc +++ b/docs/src/docs/asciidoc/guides/java-rest.adoc @@ -2,14 +2,16 @@ Rob Winch :toc: -This guide describes how to use Spring Session to transparently leverage Redis to back a web application's `HttpSession` when using REST endpoints. +This guide describes how to use Spring Session to transparently leverage Redis to back a web application's `HttpSession` when you use REST endpoints. -NOTE: The completed guide can be found in the <>. +NOTE: You can find the completed guide in the <>. == Updating Dependencies -Before you use Spring Session, you must ensure to update your dependencies. -If you are using Maven, ensure to add the following dependencies: +Before you use Spring Session, you must update your dependencies. +If you use Maven, you must add the following dependencies: + +==== .pom.xml [source,xml] [subs="verbatim,attributes"] @@ -35,11 +37,13 @@ If you are using Maven, ensure to add the following dependencies: ---- +==== ifeval::["{version-snapshot}" == "true"] -Since We are using a SNAPSHOT version, we need to ensure to add the Spring Snapshot Maven Repository. -Ensure you have the following in your pom.xml: +Since we are using a SNAPSHOT version, we need to ensure to add the Spring Snapshot Maven Repository. +You must have the following in your pom.xml: +==== .pom.xml [source,xml] ---- @@ -53,12 +57,14 @@ Ensure you have the following in your pom.xml: ---- +==== endif::[] ifeval::["{version-milestone}" == "true"] -Since We are using a Milestone version, we need to ensure to add the Spring Milestone Maven Repository. -Ensure you have the following in your pom.xml: +Since we are using a Milestone version, we need to add the Spring Milestone Maven Repository. +You msut have the following in your pom.xml: +==== .pom.xml [source,xml] ---- @@ -67,6 +73,7 @@ Ensure you have the following in your pom.xml: https://repo.spring.io/libs-milestone ---- +==== endif::[] // tag::config[] @@ -75,83 +82,103 @@ endif::[] == Spring Configuration After adding the required dependencies, we can create our Spring configuration. -The Spring configuration is responsible for creating a Servlet Filter that replaces the `HttpSession` implementation with an implementation backed by Spring Session. -Add the following Spring Configuration: +The Spring configuration is responsible for creating a servlet filter that replaces the `HttpSession` implementation with an implementation backed by Spring Session. +To do so, add the following Spring Configuration: +==== [source,java] ---- include::{samples-dir}javaconfig/rest/src/main/java/sample/HttpSessionConfig.java[tags=class] ---- -<1> The `@EnableRedisHttpSession` annotation creates a Spring Bean with the name of `springSessionRepositoryFilter` that implements `Filter`. -The filter is what is in charge of replacing the `HttpSession` implementation to be backed by Spring Session. -In this instance Spring Session is backed by Redis. +<1> The `@EnableRedisHttpSession` annotation creates a Spring bean named `springSessionRepositoryFilter` that implements `Filter`. +The filter is in charge of replacing the `HttpSession` 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, refer to the https://docs.spring.io/spring-data/data-redis/docs/{spring-data-redis-version}/reference/html/[reference documentation]. +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]. <3> We customize Spring Session's HttpSession integration to use HTTP headers to convey the current session information instead of cookies. +==== == Servlet Container Initialization Our <> 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 `Config` class. We provide the configuration in our Spring `MvcInitializer` as shown below: +In order for our `Filter` to do its magic, Spring needs to load our `Config` class. +We provide the configuration in our Spring `MvcInitializer`, as the following example shows: +==== .src/main/java/sample/mvc/MvcInitializer.java [source,java,indent=0] ---- include::{samples-dir}javaconfig/rest/src/main/java/sample/mvc/MvcInitializer.java[tags=config] ---- +==== -Last we need to ensure that our Servlet Container (i.e. Tomcat) uses our `springSessionRepositoryFilter` for every request. -Fortunately, Spring Session provides a utility class named `AbstractHttpSessionApplicationInitializer` that makes this extremely easy. Simply extend the class with the default constructor as shown below: +Last, we need to ensure that our Servlet Container (that is, Tomcat) uses our `springSessionRepositoryFilter` for every request. +Fortunately, Spring Session provides a utility class named `AbstractHttpSessionApplicationInitializer` that makes doing so easy. To do so, extend the class with the default constructor, as the following example shows: +==== .src/main/java/sample/Initializer.java [source,java] ---- include::{samples-dir}javaconfig/rest/src/main/java/sample/Initializer.java[tags=class] ---- +==== -NOTE: The name of our class (Initializer) does not matter. What is important is that we extend `AbstractHttpSessionApplicationInitializer`. +NOTE: The name of our class (`Initializer`) does not matter. What is important is that we extend `AbstractHttpSessionApplicationInitializer`. // end::config[] [[rest-sample]] -== rest Sample Application +== `rest` Sample Application -=== Running the rest Sample Application +This section describes how to use the `rest` sample application. + +=== Running the `rest` Sample Application You can run the sample by obtaining the {download-url}[source code] and invoking the following command: -[NOTE] -==== -For the sample to work, you must https://redis.io/download[install Redis 2.8+] on localhost and run it with the default port (6379). +NOTE: For the sample to work, you must https://redis.io/download[install Redis 2.8+] on localhost and run it with the default port (6379). Alternatively, you can update the `RedisConnectionFactory` to point to a Redis server. -Another option is to use https://www.docker.com/[Docker] to run Redis on localhost. See https://hub.docker.com/_/redis/[Docker Redis repository] for detailed instructions. -==== +Another option is to use https://www.docker.com/[Docker] to run Redis on localhost. +See https://hub.docker.com/_/redis/[Docker Redis repository] for detailed instructions. +==== ---- $ ./gradlew :spring-session-sample-javaconfig-rest:tomcatRun ---- +==== You should now be able to access the application at http://localhost:8080/ -=== Exploring the rest Sample Application +=== Exploring the `rest` Sample Application -Try using the application. Use your favorite REST client to request http://localhost:8080/ +You can now try to use the application. To do so, use your favorite REST client to request http://localhost:8080/ +==== +---- $ curl -v http://localhost:8080/ +---- +==== -Observe that we are prompted for basic authentication. Provide the following information for the username and password: +Note that you are prompted for basic authentication. Provide the following information for the username and password: -* **Username** *user* -* **Password** *password* +* *Username* _user- +* *Password* _password_ +Then run the following command: + +==== +---- $ curl -v http://localhost:8080/ -u user:password +---- +==== -In the output you will notice the following: +In the output, you should notice the following: +==== ---- HTTP/1.1 200 OK ... @@ -159,44 +186,62 @@ X-Auth-Token: 0dc1f6e1-c7f1-41ac-8ce2-32b6b3e57aa3 {"username":"user"} ---- +==== -Specifically, we notice the following things about our response: +Specifically, you should notice the following things about our response: -* The HTTP Status is now a 200 -* We have a header with the name of *X-Auth-Token* which contains a new session id -* The current username is displayed +* The HTTP Status is now a 200. +* We have a header a the name of `X-Auth-Token` and that contains a new session ID. +* The current username is displayed. -We can now use the *X-Auth-Token* to make another request without providing the username and password again. For example, the following outputs the username just as before: +We can now use the `X-Auth-Token` to make another request without providing the username and password again. For example, the following command outputs the username, as before: +==== +---- $ curl -v http://localhost:8080/ -H "X-Auth-Token: 0dc1f6e1-c7f1-41ac-8ce2-32b6b3e57aa3" +---- +==== -The only difference is that the session id is not provided in the response headers because we are reusing an existing session. +The only difference is that the session ID is not provided in the response headers because we are reusing an existing session. -If we invalidate the session, then the X-Auth-Token is displayed in the response with an empty value. For example, the following will invalidate our session: +If we invalidate the session, the `X-Auth-Token` is displayed in the response with an empty value. For example, the following command invalidates our session: +==== +---- $ curl -v http://localhost:8080/logout -H "X-Auth-Token: 0dc1f6e1-c7f1-41ac-8ce2-32b6b3e57aa3" +---- +==== -You will see in the output that the X-Auth-Token provides an empty String indicating that the previous session was invalidated. +You can see in the output that the `X-Auth-Token` provides an empty `String` indicating that the previous session was invalidated: +==== ---- HTTP/1.1 204 No Content ... X-Auth-Token: ---- +==== -=== How does it work? +=== How Does It Work? Spring Security interacts with the standard `HttpSession` in `SecurityContextPersistenceFilter`. Instead of using Tomcat's `HttpSession`, Spring Security is now persisting the values in Redis. -Spring Session creates a header named X-Auth-Token in your browser that contains the id of your session. +Spring Session creates a header named `X-Auth-Token` in your browser. +That header contains the ID of your session. -If you like, you can easily see that the session is created in Redis. First create a session using the following: +If you like, you can easily see that the session is created in Redis. +To do so, create a session by using the following command: +==== +---- $ curl -v http://localhost:8080/ -u user:password +---- +==== -In the output you will notice the following: +In the output, you should notice the following: +=== ---- HTTP/1.1 200 OK ... @@ -204,17 +249,32 @@ X-Auth-Token: 7e8383a4-082c-4ffe-a4bc-c40fd3363c5e {"username":"user"} ---- +==== -Now remove the session using redis-cli. For example, on a Linux based system you can type: +Now you can remove the session by using redis-cli. +For example, on a Linux based system, you can type: +==== +---- $ redis-cli keys '*' | xargs redis-cli del +---- +==== TIP: The Redis documentation has instructions for https://redis.io/topics/quickstart[installing redis-cli]. -Alternatively, you can also delete the explicit key. Enter the following into your terminal ensuring to replace `7e8383a4-082c-4ffe-a4bc-c40fd3363c5e` with the value of your SESSION cookie: +Alternatively, you can also delete the explicit key. +To do so, enter the following into your terminal, being sure to replace `7e8383a4-082c-4ffe-a4bc-c40fd3363c5e` with the value of your `SESSION` cookie: +==== +---- $ redis-cli del spring:session:sessions:7e8383a4-082c-4ffe-a4bc-c40fd3363c5e +---- +==== -We can now use the *X-Auth-Token* to make another request with the session we deleted and observe we are prompted for a authentication. For example, the following returns an HTTP 401: +We can now use the `X-Auth-Token` to make another request with the session we deleted and observe we that are prompted for authentication. For example, the following returns an HTTP 401: +==== +---- $ curl -v http://localhost:8080/ -H "X-Auth-Token: 0dc1f6e1-c7f1-41ac-8ce2-32b6b3e57aa3" +---- +==== diff --git a/docs/src/docs/asciidoc/guides/java-security.adoc b/docs/src/docs/asciidoc/guides/java-security.adoc index 44dfb54c..5c0719cb 100644 --- a/docs/src/docs/asciidoc/guides/java-security.adoc +++ b/docs/src/docs/asciidoc/guides/java-security.adoc @@ -5,12 +5,13 @@ Rob Winch This guide describes how to use Spring Session along with Spring Security. It assumes you have already applied Spring Security to your application. -NOTE: The completed guide can be found in the <>. +NOTE: You can find the completed guide in the <>. == Updating Dependencies -Before you use Spring Session, you must ensure to update your dependencies. -If you are using Maven, ensure to add the following dependencies: +Before you use Spring Session, you must update your dependencies. +If you use Maven, you must add the following dependencies: +==== .pom.xml [source,xml] [subs="verbatim,attributes"] @@ -36,11 +37,13 @@ If you are using Maven, ensure to add the following dependencies: ---- +==== ifeval::["{version-snapshot}" == "true"] -Since We are using a SNAPSHOT version, we need to ensure to add the Spring Snapshot Maven Repository. -Ensure you have the following in your pom.xml: +Since we are using a SNAPSHOT version, we need to add the Spring Snapshot Maven Repository. +You must have the following in your pom.xml: +==== .pom.xml [source,xml] ---- @@ -54,12 +57,14 @@ Ensure you have the following in your pom.xml: ---- +==== endif::[] ifeval::["{version-milestone}" == "true"] -Since We are using a Milestone version, we need to ensure to add the Spring Milestone Maven Repository. -Ensure you have the following in your pom.xml: +Since we are using a Milestone version, we need to add the Spring Milestone Maven Repository. +You must have the following in your pom.xml: +==== .pom.xml [source,xml] ---- @@ -68,107 +73,121 @@ Ensure you have the following in your pom.xml: https://repo.spring.io/libs-milestone ---- +==== endif::[] [[security-spring-configuration]] == Spring Configuration After adding the required dependencies, we can create our Spring configuration. -The Spring configuration is responsible for creating a Servlet Filter that replaces the `HttpSession` implementation with an implementation backed by Spring Session. -Add the following Spring Configuration: +The Spring configuration is responsible for creating a servlet filter that replaces the `HttpSession` implementation with an implementation backed by Spring Session. +To do so, add the following Spring Configuration: +==== [source,java] ---- include::{samples-dir}javaconfig/security/src/main/java/sample/Config.java[tags=class] ---- -<1> The `@EnableRedisHttpSession` annotation creates a Spring Bean with the name of `springSessionRepositoryFilter` that implements Filter. -The filter is what is in charge of replacing the `HttpSession` implementation to be backed by Spring Session. +<1> The `@EnableRedisHttpSession` annotation creates a Spring bean with the name of `springSessionRepositoryFilter` that implements `Filter`. +The filter is in charge of replacing the `HttpSession` 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, refer to the https://docs.spring.io/spring-data/data-redis/docs/{spring-data-redis-version}/reference/html/[reference documentation]. +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]. +==== == Servlet Container Initialization -Our <> created a Spring Bean named `springSessionRepositoryFilter` that implements `Filter`. +Our <> 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 `Config` class. -Since our application is already loading Spring configuration using our `SecurityInitializer` class, we can simply add our Config class to it. +Since our application is already loading Spring configuration by using our `SecurityInitializer` class, we can add our configuration class to it. +The following example shows how to do so: +==== .src/main/java/sample/SecurityInitializer.java [source,java] ---- include::{samples-dir}javaconfig/security/src/main/java/sample/SecurityInitializer.java[tags=class] ---- +==== -Last we need to ensure that our Servlet Container (i.e. Tomcat) uses our `springSessionRepositoryFilter` for every request. +Last, we need to ensure that our Servlet Container (that is, Tomcat) uses our `springSessionRepositoryFilter` for every request. It is extremely important that Spring Session's `springSessionRepositoryFilter` is invoked before Spring Security's `springSecurityFilterChain`. This ensures that the `HttpSession` that Spring Security uses is backed by Spring Session. -Fortunately, Spring Session provides a utility class named `AbstractHttpSessionApplicationInitializer` that makes this extremely easy. -You can find an example below: +Fortunately, Spring Session provides a utility class named `AbstractHttpSessionApplicationInitializer` that makes doing so easy. +The following example shows how to do so: +==== .src/main/java/sample/Initializer.java [source,java] ---- include::{samples-dir}javaconfig/security/src/main/java/sample/Initializer.java[tags=class] ---- +==== NOTE: The name of our class (Initializer) does not matter. What is important is that we extend `AbstractHttpSessionApplicationInitializer`. -By extending `AbstractHttpSessionApplicationInitializer` we ensure that the Spring Bean by the name `springSessionRepositoryFilter` is registered with our Servlet Container for every request before Spring Security's `springSecurityFilterChain` . +By extending `AbstractHttpSessionApplicationInitializer`, we ensure that the Spring bean named `springSessionRepositoryFilter` is registered with our Servlet Container for every request before Spring Security's `springSecurityFilterChain` . [[security-sample]] -== security Sample Application +== `security` Sample Application +This section describes how to work with the `security` sample application. - -=== Running the security Sample Application +=== Running the `security` Sample Application You can run the sample by obtaining the {download-url}[source code] and invoking the following command: -[NOTE] ==== -For the sample to work, you must https://redis.io/download[install Redis 2.8+] on localhost and run it with the default port (6379). -Alternatively, you can update the `RedisConnectionFactory` to point to a Redis server. -Another option is to use https://www.docker.com/[Docker] to run Redis on localhost. See https://hub.docker.com/_/redis/[Docker Redis repository] for detailed instructions. -==== - ---- $ ./gradlew :spring-session-sample-javaconfig-security:tomcatRun ---- +==== + +NOTE: For the sample to work, you must https://redis.io/download[install Redis 2.8+] on localhost and run it with the default port (6379). +Alternatively, you can update the `RedisConnectionFactory` to point to a Redis server. +Another option is to use https://www.docker.com/[Docker] to run Redis on localhost. +See https://hub.docker.com/_/redis/[Docker Redis repository] for detailed instructions. You should now be able to access the application at http://localhost:8080/ -=== Exploring the security Sample Application +=== Exploring the `security` Sample Application -Try using the application. Enter the following to log in: +Now you can use the application. Enter the following to log in: -* **Username** _user_ -* **Password** _password_ +* *Username* _user_ +* *Password* _password_ -Now click the **Login** button. +Now click the *Login* button. You should now see a message indicating your are logged in with the user entered previously. The user's information is stored in Redis rather than Tomcat's `HttpSession` implementation. -=== How does it work? +=== How Does It Work? -Instead of using Tomcat's `HttpSession`, we are actually persisting the values in Redis. +Instead of using Tomcat's `HttpSession`, we persist the values in Redis. Spring Session replaces the `HttpSession` with an implementation that is backed by Redis. -When Spring Security's `SecurityContextPersistenceFilter` saves the `SecurityContext` to the `HttpSession` it is then persisted into Redis. +When Spring Security's `SecurityContextPersistenceFilter` saves the `SecurityContext` to the `HttpSession`, it is then persisted into Redis. -When a new `HttpSession` is created, Spring Session creates a cookie named SESSION in your browser that contains the id of your session. -Go ahead and view the cookies (click for help with https://developers.google.com/web/tools/chrome-devtools/manage-data/cookies[Chrome] or https://developer.mozilla.org/en-US/docs/Tools/Storage_Inspector[Firefox]). +When a new `HttpSession` is created, Spring Session creates a cookie named `SESSION` in your browser. +That cookie contains the ID of your session. +You can view the cookies (with https://developers.google.com/web/tools/chrome-devtools/manage-data/cookies[Chrome] or https://developer.mozilla.org/en-US/docs/Tools/Storage_Inspector[Firefox]). -If you like, you can easily remove the session using redis-cli. For example, on a Linux based system you can type: +You can remove the session using redis-cli. For example, on a Linux-based system you can type the following command: +==== +---- $ redis-cli keys '*' | xargs redis-cli del +---- +==== TIP: The Redis documentation has instructions for https://redis.io/topics/quickstart[installing redis-cli]. -Alternatively, you can also delete the explicit key. Enter the following into your terminal ensuring to replace `7e8383a4-082c-4ffe-a4bc-c40fd3363c5e` with the value of your SESSION cookie: +Alternatively, you can also delete the explicit key. +Enter the following command into your terminal, being sure to replace `7e8383a4-082c-4ffe-a4bc-c40fd3363c5e` with the value of your `SESSION` cookie: $ redis-cli del spring:session:sessions:7e8383a4-082c-4ffe-a4bc-c40fd3363c5e -Now visit the application at http://localhost:8080/ and observe that we are no longer authenticated. +Now you can visit the application at http://localhost:8080/ and see that we are no longer authenticated. diff --git a/docs/src/docs/asciidoc/guides/xml-jdbc.adoc b/docs/src/docs/asciidoc/guides/xml-jdbc.adoc index 4307f94d..483ccef6 100644 --- a/docs/src/docs/asciidoc/guides/xml-jdbc.adoc +++ b/docs/src/docs/asciidoc/guides/xml-jdbc.adoc @@ -4,12 +4,14 @@ Rob Winch, Vedran Pavić This guide describes how to use Spring Session to transparently leverage a relational to back a web application's `HttpSession` with XML based configuration. -NOTE: The completed guide can be found in the <>. +NOTE: You can find the completed guide in the <>. == Updating Dependencies -Before you use Spring Session, you must ensure to update your dependencies. -If you are using Maven, ensure to add the following dependencies: +Before you use Spring Session, you must update your dependencies. +If you are using Maven, you must add the following dependencies: + +==== .pom.xml [source,xml] [subs="verbatim,attributes"] @@ -30,11 +32,13 @@ If you are using Maven, ensure to add the following dependencies: ---- +==== ifeval::["{version-snapshot}" == "true"] -Since we are using a SNAPSHOT version, we need to ensure to add the Spring Snapshot Maven Repository. -Ensure you have the following in your pom.xml: +Since we are using a SNAPSHOT version, we need to add the Spring Snapshot Maven Repository. +You must have the following in your pom.xml: +==== .pom.xml [source,xml] ---- @@ -48,12 +52,14 @@ Ensure you have the following in your pom.xml: ---- +==== endif::[] ifeval::["{version-milestone}" == "true"] -Since We are using a Milestone version, we need to ensure to add the Spring Milestone Maven Repository. -Ensure you have the following in your pom.xml: +Since we are using a Milestone version, we need to add the Spring Milestone Maven Repository. +You must have the following in your pom.xml: +==== .pom.xml [source,xml] ---- @@ -63,6 +69,7 @@ Ensure you have the following in your pom.xml: ---- endif::[] +==== // tag::config[] @@ -70,9 +77,10 @@ endif::[] == Spring XML Configuration After adding the required dependencies, we can create our Spring configuration. -The Spring configuration is responsible for creating a Servlet Filter that replaces the `HttpSession` implementation with an implementation backed by Spring Session. -Add the following Spring Configuration: +The Spring configuration is responsible for creating a servlet filter that replaces the `HttpSession` implementation with an implementation backed by Spring Session. +The following listing shows how to add the following Spring Configuration: +==== .src/main/webapp/WEB-INF/spring/session.xml [source,xml,indent=0] ---- @@ -80,83 +88,94 @@ include::{samples-dir}xml/jdbc/src/main/webapp/WEB-INF/spring/session.xml[tags=b ---- <1> We use the combination of `` and `JdbcHttpSessionConfiguration` because Spring Session does not yet provide XML Namespace support (see https://github.com/spring-projects/spring-session/issues/104[gh-104]). -This creates a Spring Bean with the name of `springSessionRepositoryFilter` that implements Filter. -The filter is what is in charge of replacing the `HttpSession` implementation to be backed by Spring Session. -In this instance Spring Session is backed by a relational database. -<2> We create a `dataSource` that connects Spring Session to an embedded instance of H2 database. -We configure the H2 database to create database tables using the SQL script which is included in Spring Session. +This creates a Spring bean with the name of `springSessionRepositoryFilter`. +That bean implements `Filter`. +The filter is in charge of replacing the `HttpSession` implementation to be backed by Spring Session. +In this instance, Spring Session is backed by a relational database. +<2> We create a `dataSource` that connects Spring Session to an embedded instance of an H2 database. +We configure the H2 database to create database tables by using the SQL script that is included in Spring Session. <3> We create a `transactionManager` that manages transactions for previously configured `dataSource`. +==== -For additional information on how to configure data access related concerns, please refer to the https://docs.spring.io/spring/docs/{spring-framework-version}/spring-framework-reference/data-access.html[Spring Framework Reference Documentation]. +For additional information on how to configure data access-related concerns, see the https://docs.spring.io/spring/docs/{spring-framework-version}/spring-framework-reference/data-access.html[Spring Framework Reference Documentation]. == XML Servlet Container Initialization -Our <> created a Spring Bean named `springSessionRepositoryFilter` that implements `Filter`. +Our <> 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, we need to instruct Spring to load our `session.xml` configuration. -We do this with the following configuration: - +We do so with the following configuration: +==== .src/main/webapp/WEB-INF/web.xml [source,xml,indent=0] ---- include::{samples-dir}xml/jdbc/src/main/webapp/WEB-INF/web.xml[tags=context-param] include::{samples-dir}xml/jdbc/src/main/webapp/WEB-INF/web.xml[tags=listeners] ---- +==== -The https://docs.spring.io/spring/docs/{spring-framework-version}/spring-framework-reference/core.html#context-create[ContextLoaderListener] reads the contextConfigLocation and picks up our session.xml configuration. +The https://docs.spring.io/spring/docs/{spring-framework-version}/spring-framework-reference/core.html#context-create[`ContextLoaderListener`] reads the `contextConfigLocation` and picks up our session.xml configuration. -Last we need to ensure that our Servlet Container (i.e. Tomcat) uses our `springSessionRepositoryFilter` for every request. +Last, we need to ensure that our Servlet Container (that is, Tomcat) uses our `springSessionRepositoryFilter` for every request. The following snippet performs this last step for us: +==== .src/main/webapp/WEB-INF/web.xml [source,xml,indent=0] ---- include::{samples-dir}xml/jdbc/src/main/webapp/WEB-INF/web.xml[tags=springSessionRepositoryFilter] ---- +==== -The https://docs.spring.io/spring-framework/docs/{spring-framework-version}/javadoc-api/org/springframework/web/filter/DelegatingFilterProxy.html[DelegatingFilterProxy] will look up a Bean by the name of `springSessionRepositoryFilter` and cast it to a `Filter`. -For every request that `DelegatingFilterProxy` is invoked, the `springSessionRepositoryFilter` will be invoked. +The https://docs.spring.io/spring-framework/docs/{spring-framework-version}/javadoc-api/org/springframework/web/filter/DelegatingFilterProxy.html[`DelegatingFilterProxy`] looks up a bean named `springSessionRepositoryFilter` and casts it to a `Filter`. +For every request on which `DelegatingFilterProxy` is invoked, the `springSessionRepositoryFilter` is invoked. // end::config[] [[httpsession-jdbc-xml-sample]] -== httpsession-jdbc-xml Sample Application +== `httpsession-jdbc-xml` Sample Application -=== Running the httpsession-jdbc-xml Sample Application +This section describes how to work with the `httpsession-jdbc-xml` Sample Application. + +=== Running the `httpsession-jdbc-xml` Sample Application You can run the sample by obtaining the {download-url}[source code] and invoking the following command: +==== ---- $ ./gradlew :spring-session-sample-xml-jdbc:tomcatRun ---- +==== You should now be able to access the application at http://localhost:8080/ -=== Exploring the httpsession-jdbc-xml Sample Application +=== Exploring the `httpsession-jdbc-xml` Sample Application -Try using the application. Fill out the form with the following information: +Now you can try using the application. To do so, fill out the form with the following information: -* **Attribute Name:** _username_ -* **Attribute Value:** _rob_ +* *Attribute Name:* _username_ +* *Attribute Value:* _rob_ -Now click the **Set Attribute** button. You should now see the values displayed in the table. +Now click the *Set Attribute* button. You should now see the values displayed in the table. -=== How does it work? +=== How Does It Work? -We interact with the standard `HttpSession` in the `SessionServlet` shown below: +We interact with the standard `HttpSession` in the following `SessionServlet`: +==== .src/main/java/sample/SessionServlet.java [source,java] ---- include::{samples-dir}xml/jdbc/src/main/java/sample/SessionServlet.java[tags=class] ---- +==== -Instead of using Tomcat's `HttpSession`, we are actually persisting the values in H2 database. -Spring Session creates a cookie named SESSION in your browser that contains the id of your session. -Go ahead and view the cookies (click for help with https://developers.google.com/web/tools/chrome-devtools/manage-data/cookies[Chrome] or https://developer.mozilla.org/en-US/docs/Tools/Storage_Inspector[Firefox]). +Instead of using Tomcat's `HttpSession`, we persist the values in the H2 database. +Spring Session creates a cookie named `SESSION` in your browser. That cookie contains the ID of your session. +You can view the cookies (with https://developers.google.com/web/tools/chrome-devtools/manage-data/cookies[Chrome] or https://developer.mozilla.org/en-US/docs/Tools/Storage_Inspector[Firefox]). -If you like, you can easily remove the session using H2 web console available at: http://localhost:8080/h2-console/ (use `jdbc:h2:mem:testdb` for JDBC URL) +You can remove the session by using H2 web console available at: http://localhost:8080/h2-console/ (use `jdbc:h2:mem:testdb` for JDBC URL) -Now visit the application at http://localhost:8080/ and observe that the attribute we added is no longer displayed. +Now you can visit the application at http://localhost:8080/ and observe that the attribute we added is no longer displayed. diff --git a/docs/src/docs/asciidoc/guides/xml-redis.adoc b/docs/src/docs/asciidoc/guides/xml-redis.adoc index daf11069..fec86bd9 100644 --- a/docs/src/docs/asciidoc/guides/xml-redis.adoc +++ b/docs/src/docs/asciidoc/guides/xml-redis.adoc @@ -2,14 +2,15 @@ Rob Winch :toc: -This guide describes how to use Spring Session to transparently leverage Redis to back a web application's `HttpSession` with XML based configuration. +This guide describes how to use Spring Session to transparently leverage Redis to back a web application's `HttpSession` with XML-based configuration. -NOTE: The completed guide can be found in the <>. +NOTE: You can find the completed guide in the <>. == Updating Dependencies -Before you use Spring Session, you must ensure to update your dependencies. -If you are using Maven, ensure to add the following dependencies: +Before you use Spring Session, you must update your dependencies. +If you use Maven, you must add the following dependencies: +==== .pom.xml [source,xml] [subs="verbatim,attributes"] @@ -35,11 +36,13 @@ If you are using Maven, ensure to add the following dependencies: ---- +==== ifeval::["{version-snapshot}" == "true"] -Since we are using a SNAPSHOT version, we need to ensure to add the Spring Snapshot Maven Repository. -Ensure you have the following in your pom.xml: +Since we are using a SNAPSHOT version, we need to add the Spring Snapshot Maven Repository. +You must have the following in your pom.xml: +==== .pom.xml [source,xml] ---- @@ -53,12 +56,14 @@ Ensure you have the following in your pom.xml: ---- +==== endif::[] ifeval::["{version-milestone}" == "true"] -Since We are using a Milestone version, we need to ensure to add the Spring Milestone Maven Repository. -Ensure you have the following in your pom.xml: +Since we are using a Milestone version, we need to add the Spring Milestone Maven Repository. +You must have the following in your pom.xml: +==== .pom.xml [source,xml] ---- @@ -67,6 +72,7 @@ Ensure you have the following in your pom.xml: https://repo.spring.io/libs-milestone ---- +==== endif::[] // tag::config[] @@ -75,9 +81,10 @@ endif::[] == Spring XML Configuration After adding the required dependencies, we can create our Spring configuration. -The Spring configuration is responsible for creating a Servlet Filter that replaces the `HttpSession` implementation with an implementation backed by Spring Session. -Add the following Spring Configuration: +The Spring configuration is responsible for creating a servlet filter that replaces the `HttpSession` implementation with an implementation backed by Spring Session. +To do so, add the following Spring Configuration: +==== .src/main/webapp/WEB-INF/spring/session.xml [source,xml,indent=0] ---- @@ -85,12 +92,13 @@ include::{samples-dir}xml/redis/src/main/webapp/WEB-INF/spring/session.xml[tags= ---- <1> We use the combination of `` and `RedisHttpSessionConfiguration` because Spring Session does not yet provide XML Namespace support (see https://github.com/spring-projects/spring-session/issues/104[gh-104]). -This creates a Spring Bean with the name of `springSessionRepositoryFilter` that implements Filter. -The filter is what is in charge of replacing the `HttpSession` implementation to be backed by Spring Session. -In this instance Spring Session is backed by Redis. +This creates a Spring Bean with the name of `springSessionRepositoryFilter` that implements `Filter`. +The filter is in charge of replacing the `HttpSession` 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, refer to the https://docs.spring.io/spring-data/data-redis/docs/{spring-data-redis-version}/reference/html/[reference documentation]. +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]. +==== == XML Servlet Container Initialization @@ -98,83 +106,99 @@ Our <> created a Spri 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, we need to instruct Spring to load our `session.xml` configuration. -We do this with the following configuration: - +We can do so with the following configuration: +==== .src/main/webapp/WEB-INF/web.xml [source,xml,indent=0] ---- include::{samples-dir}xml/redis/src/main/webapp/WEB-INF/web.xml[tags=context-param] include::{samples-dir}xml/redis/src/main/webapp/WEB-INF/web.xml[tags=listeners] ---- +==== -The https://docs.spring.io/spring/docs/{spring-framework-version}/spring-framework-reference/core.html#context-create[ContextLoaderListener] reads the contextConfigLocation and picks up our session.xml configuration. +The https://docs.spring.io/spring/docs/{spring-framework-version}/spring-framework-reference/core.html#context-create[`ContextLoaderListener`] reads the contextConfigLocation and picks up our session.xml configuration. -Last we need to ensure that our Servlet Container (i.e. Tomcat) uses our `springSessionRepositoryFilter` for every request. +Last, we need to ensure that our Servlet Container (that is, Tomcat) uses our `springSessionRepositoryFilter` for every request. The following snippet performs this last step for us: +==== .src/main/webapp/WEB-INF/web.xml [source,xml,indent=0] ---- include::{samples-dir}xml/redis/src/main/webapp/WEB-INF/web.xml[tags=springSessionRepositoryFilter] ---- +==== -The https://docs.spring.io/spring-framework/docs/{spring-framework-version}/javadoc-api/org/springframework/web/filter/DelegatingFilterProxy.html[DelegatingFilterProxy] will look up a Bean by the name of `springSessionRepositoryFilter` and cast it to a `Filter`. -For every request that `DelegatingFilterProxy` is invoked, the `springSessionRepositoryFilter` will be invoked. +The https://docs.spring.io/spring-framework/docs/{spring-framework-version}/javadoc-api/org/springframework/web/filter/DelegatingFilterProxy.html[`DelegatingFilterProxy`] looks up a Bean by the name of `springSessionRepositoryFilter` and cast it to a `Filter`. +For every request that `DelegatingFilterProxy` is invoked, the `springSessionRepositoryFilter` is invoked. // end::config[] [[httpsession-xml-sample]] -== httpsession-xml Sample Application +== `httpsession-xml` Sample Application -=== Running the httpsession-xml Sample Application +This section describes how to work with the `httpsession-xml` sample application. + +=== Running the `httpsession-xml` Sample Application You can run the sample by obtaining the {download-url}[source code] and invoking the following command: -[NOTE] -==== -For the sample to work, you must https://redis.io/download[install Redis 2.8+] on localhost and run it with the default port (6379). +NOTE: For the sample to work, you must https://redis.io/download[install Redis 2.8+] on localhost and run it with the default port (6379). Alternatively, you can update the `RedisConnectionFactory` to point to a Redis server. Another option is to use https://www.docker.com/[Docker] to run Redis on localhost. See https://hub.docker.com/_/redis/[Docker Redis repository] for detailed instructions. -==== +==== ---- $ ./gradlew :spring-session-sample-xml-redis:tomcatRun ---- +==== You should now be able to access the application at http://localhost:8080/ -=== Exploring the httpsession-xml Sample Application +=== Exploring the `httpsession-xml` Sample Application -Try using the application. Fill out the form with the following information: +Now you can try using the application. Fill out the form with the following information: -* **Attribute Name:** _username_ -* **Attribute Value:** _rob_ +* *Attribute Name:* _username_ +* *Attribute Value:* _rob_ -Now click the **Set Attribute** button. You should now see the values displayed in the table. +Now click the *Set Attribute* button. You should now see the values displayed in the table. -=== How does it work? +=== How Does It Work? -We interact with the standard `HttpSession` in the `SessionServlet` shown below: +We interact with the standard `HttpSession` in the `SessionServlet` shown in the following listing: +==== .src/main/java/sample/SessionServlet.java [source,java] ---- include::{samples-dir}xml/redis/src/main/java/sample/SessionServlet.java[tags=class] ---- +==== -Instead of using Tomcat's `HttpSession`, we are actually persisting the values in Redis. -Spring Session creates a cookie named SESSION in your browser that contains the id of your session. -Go ahead and view the cookies (click for help with https://developers.google.com/web/tools/chrome-devtools/manage-data/cookies[Chrome] or https://developer.mozilla.org/en-US/docs/Tools/Storage_Inspector[Firefox]). +Instead of using Tomcat's `HttpSession`, we persist the values in Redis. +Spring Session creates a cookie named SESSION in your browser. +That cookie contains the ID of your session. +You can view the cookies (with https://developers.google.com/web/tools/chrome-devtools/manage-data/cookies[Chrome] or https://developer.mozilla.org/en-US/docs/Tools/Storage_Inspector[Firefox]). -If you like, you can easily remove the session using redis-cli. For example, on a Linux based system you can type: +You can remove the session using redis-cli. +For example, on a Linux based system you can type the following: +==== +---- $ redis-cli keys '*' | xargs redis-cli del +---- +==== TIP: The Redis documentation has instructions for https://redis.io/topics/quickstart[installing redis-cli]. -Alternatively, you can also delete the explicit key. Enter the following into your terminal ensuring to replace `7e8383a4-082c-4ffe-a4bc-c40fd3363c5e` with the value of your SESSION cookie: +Alternatively, you can also delete the explicit key. To do so, enter the following into your terminal, being sure to replace `7e8383a4-082c-4ffe-a4bc-c40fd3363c5e` with the value of your SESSION cookie: +==== +---- $ redis-cli del spring:session:sessions:7e8383a4-082c-4ffe-a4bc-c40fd3363c5e +---- +==== -Now visit the application at http://localhost:8080/ and observe that the attribute we added is no longer displayed. +Now you can visit the application at http://localhost:8080/ and see that the attribute we added is no longer displayed. diff --git a/docs/src/docs/asciidoc/index.adoc b/docs/src/docs/asciidoc/index.adoc index 02452ac6..749e7ab4 100644 --- a/docs/src/docs/asciidoc/index.adoc +++ b/docs/src/docs/asciidoc/index.adoc @@ -1,35 +1,26 @@ = Spring Session -Rob Winch, Vedran Pavić +Rob Winch; Vedran Pavić; Jay Bryant :doctype: book :indexdoc-tests: {docs-test-dir}docs/IndexDocTests.java :websocketdoc-test-dir: {docs-test-dir}docs/websocket/ :toc: left [[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. +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 (i.e. Tomcat) 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. +* <>: 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 in 2.0 -Below are the highlights of what is new in Spring Session 2.0. You can find a complete list of what's new by referring to the changelogs of -https://github.com/spring-projects/spring-session/milestone/17?closed=1[2.0.0.M1], -https://github.com/spring-projects/spring-session/milestone/22?closed=1[2.0.0.M2], -https://github.com/spring-projects/spring-session/milestone/23?closed=1[2.0.0.M3], -https://github.com/spring-projects/spring-session/milestone/24?closed=1[2.0.0.M4], -https://github.com/spring-projects/spring-session/milestone/25?closed=1[2.0.0.M5], -https://github.com/spring-projects/spring-session/milestone/26?closed=1[2.0.0.RC1], -https://github.com/spring-projects/spring-session/milestone/27?closed=1[2.0.0.RC2], and -https://github.com/spring-projects/spring-session/milestone/30?closed=1[2.0.0.RELEASE]. +The following list highlights what is new in Spring Session 2.0: * Upgraded to Java 8 and Spring Framework 5 as baseline * https://github.com/spring-projects/spring-session/issues/683[Added support for managing Spring WebFlux's `WebSession`] with https://github.com/spring-projects/spring-session/issues/816[Redis `ReactiveSessionRepository`] @@ -39,12 +30,23 @@ https://github.com/spring-projects/spring-session/milestone/30?closed=1[2.0.0.RE * https://github.com/spring-projects/spring-session/pull/713[Added support for configuring default `CookieSerializer` using `SessionCookieConfig`] * Lots of performance improvements and bug fixes +You can find a complete list of what is new by referring to the changelogs of + +* https://github.com/spring-projects/spring-session/milestone/17?closed=1[2.0.0.M1] +* https://github.com/spring-projects/spring-session/milestone/22?closed=1[2.0.0.M2] +* https://github.com/spring-projects/spring-session/milestone/23?closed=1[2.0.0.M3] +* https://github.com/spring-projects/spring-session/milestone/24?closed=1[2.0.0.M4] +* https://github.com/spring-projects/spring-session/milestone/25?closed=1[2.0.0.M5] +* https://github.com/spring-projects/spring-session/milestone/26?closed=1[2.0.0.RC1] +* https://github.com/spring-projects/spring-session/milestone/27?closed=1[2.0.0.RC2] +* https://github.com/spring-projects/spring-session/milestone/30?closed=1[2.0.0.RELEASE] + [[samples]] == Samples and Guides (Start Here) -If you are looking to get started with Spring Session, the best place to start is our Sample Applications. +To get started with Spring Session, the best place to start is our Sample Applications. -.Sample Applications using Spring Boot +.Sample Applications that use Spring Boot |=== | Source | Description | Guide @@ -66,15 +68,15 @@ If you are looking to get started with Spring Session, the best place to start i | {gh-samples-url}boot/webflux[WebFlux] | Demonstrates how to use Spring Session to replace the Spring WebFlux's `WebSession` with Redis. -| TBD +| | {gh-samples-url}boot/redis-json[HttpSession with Redis JSON serialization] | Demonstrates how to use Spring Session to replace the `HttpSession` with Redis using JSON serialization. -| TBD +| |=== -.Sample Applications using Spring Java based configuration +.Sample Applications that use Spring Java-based configuration |=== | Source | Description | Guide @@ -104,7 +106,7 @@ If you are looking to get started with Spring Session, the best place to start i |=== -.Sample Applications using Spring XML based configuration +.Sample Applications that use Spring XML-based configuration |=== | Source | Description | Guide @@ -118,7 +120,7 @@ If you are looking to get started with Spring Session, the best place to start i |=== -.Misc sample Applications +.Miscellaneous sample Applications |=== | Source | Description | Guide @@ -135,105 +137,106 @@ If you are looking to get started with Spring Session, the best place to start i [[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 wasn't sustainable long-term as more features and `SessionRepository` implementations were added to the project. +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 up to Spring Session Core module, and several other modules that carry `SessionRepository` implementations and functionality related to the specific data store. -The users of Spring Data will 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 a part of this split, the Spring Session Data MongoDB and Spring Session Data GemFire modules were moved to separate repositories so the situation with project's repositories/modules is a follows: +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 Spring Session Core, Spring Session Data Redis, Spring Session JDBC and Spring Session Hazelcast modules +** 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 Spring Session Data MongoDB module +** Hosts the Spring Session Data MongoDB module * https://github.com/spring-projects/spring-session-data-geode[`spring-session-data-geode` repository] -** Hosts Spring Session Data Geode and Spring Session Data Geode modules +** Hosts the Spring Session Data Geode and Spring Session Data Geode modules -Finally, Spring Session now also provides a Maven BOM (as in "bill of materials") module in order to help users with version management concerns: +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 Spring Session BOM module +** Hosts the Spring Session BOM module [[httpsession]] -== HttpSession Integration +== `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 & HttpSession? +=== 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 allows providing session IDs in headers to work with <> +* *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 +=== `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 using either: +You can choose from enabling this by using either: -* <> -* <> +* <> +* <> [[httpsession-redis-jc]] -==== Redis Java Based Configuration +==== Redis Java-based Configuration -This section describes how to use Redis to back `HttpSession` using Java based configuration. +This section describes how to use Redis to back `HttpSession` by using Java based configuration. -NOTE: The <> provides a working sample on how to integrate Spring Session and `HttpSession` using Java configuration. -You can read the basic steps for integration below, but you are encouraged to follow along with the detailed HttpSession Guide when integrating with your own application. +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 +==== Redis XML-based Configuration -This section describes how to use Redis to back `HttpSession` using XML based configuration. +This section describes how to use Redis to back `HttpSession` by using XML based configuration. -NOTE: The <> provides a working sample on how to integrate Spring Session and `HttpSession` using XML configuration. -You can read the basic steps for integration below, but you are encouraged to follow along with the detailed HttpSession XML Guide when integrating with your own application. +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 +=== `HttpSession` with JDBC -Using Spring Session with `HttpSession` is enabled by adding a Servlet Filter before anything that uses the `HttpSession`. -You can choose from enabling this using either: +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 +==== JDBC Java-based Configuration -This section describes how to use a relational database to back `HttpSession` using 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 on how to integrate Spring Session and `HttpSession` using Java configuration. -You can read the basic steps for integration below, but you are encouraged to follow along with the detailed HttpSession JDBC Guide when integrating with your own application. +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 +==== JDBC XML-based Configuration -This section describes how to use a relational database to back `HttpSession` using 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 on how to integrate Spring Session and `HttpSession` using XML configuration. -You can read the basic steps for integration below, but you are encouraged to follow along with the detailed HttpSession JDBC XML Guide when integrating with your own application. +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 +==== JDBC Spring Boot-based Configuration -This section describes how to use a relational database to back `HttpSession` when using Spring Boot. +This section describes how to use a relational database to back `HttpSession` when you use Spring Boot. -NOTE: The <> provides a working sample on how to integrate Spring Session and `HttpSession` using Spring Boot. -You can read the basic steps for integration below, but you are encouraged to follow along with the detailed HttpSession JDBC Spring Boot Guide when integrating with your own application. +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] @@ -242,24 +245,25 @@ include::guides/boot-jdbc.adoc[tags=config,leveloffset=+3] 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` using Java based configuration. +This section describes how to use Hazelcast to back `HttpSession` by using Java-based configuration. -NOTE: The <> provides a working sample on how to integrate Spring Session and `HttpSession` using Java configuration. -You can read the basic steps for integration below, but you are encouraged to follow along with the detailed Hazelcast Spring Guide when integrating with your own application. +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 +=== How `HttpSession` Integration Works -Fortunately both `HttpSession` and `HttpServletRequest` (the API for obtaining an `HttpSession`) are both interfaces. +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`. The intent is so that user's can understand what is happening under the covers. This functionality is already integrated and you do NOT need to implement this logic yourself. +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`. +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 { @@ -279,13 +283,15 @@ public class SessionRepositoryRequestWrapper extends HttpServletRequestWrapper { // ... other methods delegate to the original HttpServletRequest ... } ---- +==== Any method that returns an `HttpSession` is overridden. -All other methods are implemented by `HttpServletRequestWrapper` and simply delegate to the original `HttpServletRequest` implementation. +All other methods are implemented by `HttpServletRequestWrapper` and delegate to the original `HttpServletRequest` implementation. -We replace the `HttpServletRequest` implementation using a servlet `Filter` called `SessionRepositoryFilter`. -The pseudocode can be found below: +We replace the `HttpServletRequest` implementation by using a servlet `Filter` called `SessionRepositoryFilter`. +The pseudocode belows: +==== [source, java] ---- public class SessionRepositoryFilter implements Filter { @@ -301,23 +307,23 @@ public class SessionRepositoryFilter implements Filter { // ... } ---- +==== -By passing in 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` must be placed before anything that interacts with the `HttpSession`. +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 & RESTful APIs +=== `HttpSession` and RESTful APIs -Spring Session can work with RESTful APIs by allowing the session to be provided in a header. +Spring Session can work with RESTful APIs by letting the session be provided in a header. - -NOTE: The <> provides a working sample on how to use Spring Session in a REST application to support authenticating with a header. -You can follow the basic steps for integration below, but you are encouraged to follow along with the detailed REST Guide when integrating with your own application. +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]] -=== HttpSessionListener +=== Using `HttpSessionListener` Spring Session supports `HttpSessionListener` by translating `SessionDestroyedEvent` and `SessionCreatedEvent` into `HttpSessionEvent` by declaring `SessionEventHttpSessionListenerAdapter`. To use this support, you need to: @@ -326,21 +332,25 @@ To use this support, you need to: * Configure `SessionEventHttpSessionListenerAdapter` as a Spring bean. * Inject every `HttpSessionListener` into the `SessionEventHttpSessionListenerAdapter` -If you are using the configuration support documented in <>, then 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` you can simply add `HttpSessionEventPublisher` as a bean. -In Java configuration, this might look like: +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: +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 @@ -350,26 +360,26 @@ Spring Session provides transparent integration with Spring's WebSocket support. include::guides/boot-websocket.adoc[tags=disclaimer,leveloffset=+1] [[websocket-why]] -=== Why Spring Session & WebSockets? +=== Why Spring Session and WebSockets? -So why do we need Spring Session when using 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 pretty poor user experience. +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, then we will also disconnect from our conversation! +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 on how to integrate Spring Session with WebSockets. -You can follow the basic steps for integration below, but you are encouraged to follow along with the detailed WebSocket Guide when integrating with your own application: +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 +==== `HttpSession` Integration Before using WebSocket integration, you should be sure that you have <> working first. @@ -379,10 +389,10 @@ include::guides/boot-websocket.adoc[tags=config,leveloffset=+2] == WebSession Integration Spring Session provides transparent integration with Spring WebFlux's `WebSession`. -This means that developers can switch the `WebSession` implementation out with an implementation that is backed by Spring Session. +This means that you can switch the `WebSession` implementation out with an implementation that is backed by Spring Session. [[websession-why]] -=== Why Spring Session & WebSession? +=== 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. @@ -390,10 +400,11 @@ As with `HttpSession`, Spring Session makes it trivial to support < @@ -407,24 +418,26 @@ public class SessionConfiguration { } ---- -<1> The `@EnableRedisWebSession` annotation creates a Spring Bean with the name of `webSessionManager` that implements the `WebSessionManager`. +<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. +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, refer to the https://docs.spring.io/spring-data/data-redis/docs/{spring-data-redis-version}/reference/html/[reference documentation]. +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 -With Spring WebFlux and it's `WebSession` things are considerably simpler for Spring Session to integrate with, compared to Servlet API and it's `HttpSession`. -Spring WebFlux provides `WebSessionStore` API which presents a strategy for persisting `WebSession`. +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`. The intent is so that user's can understand what is happening under the covers. This functionality is already integrated and you do NOT need to implement this logic yourself. +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`. +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 { @@ -465,9 +478,11 @@ public class SpringSessionWebSession implements WebSession { // ... 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: +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 { @@ -481,9 +496,10 @@ public class SpringSessionWebSessionStore implements WebSessi // ... } ---- +==== -In order to be detected by Spring WebFlux, this custom `WebSessionStore` needs to be registered with `ApplicationContext` as bean named `webSessionManager`. -For additional information on Spring WebFlux, refer to the https://docs.spring.io/spring/docs/{spring-framework-version}/spring-framework-reference/web-reactive.html[Spring Framework Reference Documentation]. +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/docs/{spring-framework-version}/spring-framework-reference/web-reactive.html[Spring Framework Reference Documentation]. [[spring-security]] == Spring Security Integration @@ -491,18 +507,19 @@ For additional information on Spring WebFlux, refer to the https://docs.spring.i Spring Session provides integration with Spring Security. [[spring-security-rememberme]] -=== Spring Security Remember-Me Support +=== 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 will: +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: -* Change the session expiration length -* Ensure the session cookie expires at `Integer.MAX_VALUE`. -The cookie expiration is set to the largest possible value because the cookie is only set when the session is created. -If it were set to the same value as the session expiration, then the session would get renewed when the user used it but the cookie expiration would not be updated causing the expiration to be fixed. +* 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 use the following as a guide: +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] @@ -510,39 +527,47 @@ include::{docs-test-dir}docs/security/RememberMeSecurityConfiguration.java[tags= include::{docs-test-dir}docs/security/RememberMeSecurityConfiguration.java[tags=rememberme-bean] ---- +==== -An XML based configuration would look something like this: +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 will also work in a clustered environment. This is done by providing a custom +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` like this: +`SessionManagementConfigurer`, as the following listing shows: + +==== [source,java,indent=0] ---- include::{docs-test-dir}docs/security/SecurityConfiguration.java[tags=class] ---- +==== -This assumes that you've also configured Spring Session to provide a `FindByIndexNameSessionRepository` that +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 this: +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. @@ -551,183 +576,207 @@ This assumes that your Spring Session `SessionRegistry` bean is called `sessionR === Limitations Spring Session's implementation of Spring Security's `SessionRegistry` interface does not support the `getAllPrincipals` -method, as this information cannot be retrieved using Spring Session. This method is never called by Spring Security, -so this only affects applications that access the `SessionRegistry` themselves. +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 -You can browse the complete link:../../api/[Javadoc] online. The key APIs are described below: +You can browse the complete link:../../api/[Javadoc] online. The key APIs are described in the following sections: + +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> [[api-session]] -=== Session +=== Using `Session` A `Session` is a simplified `Map` of name value pairs. -Typical usage might look like the following: +Typical usage might look like the following listing: +==== [source,java,indent=0] ---- include::{indexdoc-tests}[tags=repository-demo] ---- <1> We create a `SessionRepository` instance with a generic type, `S`, that extends `Session`. The generic type is defined in our class. -<2> We create a new `Session` using our `SessionRepository` and assign it to a variable of type `S`. +<2> We create a new `Session` by using our `SessionRepository` and assign it to a variable of type `S`. <3> We interact with the `Session`. In our example, we demonstrate saving a `User` to the `Session`. -<4> We now save the `Session`. This is why we needed the generic type `S`. The `SessionRepository` only allows saving `Session` instances that were created or retrieved using the same `SessionRepository`. This allows for the `SessionRepository` to make implementation specific optimizations (i.e. only writing attributes that have changed). +<4> We now save the `Session`. This is why we needed the generic type `S`. The `SessionRepository` only allows saving `Session` instances that were created or retrieved by using the same `SessionRepository`. This allows for the `SessionRepository` to make implementation specific optimizations (that is, writing only attributes that have changed). <5> We retrieve the `Session` from the `SessionRepository`. <6> We obtain the persisted `User` from our `Session` without the need for explicitly casting our attribute. +==== -`Session` API also provides attributes related to the `Session` instance's expiration. +The `Session` API also provides attributes related to the `Session` instance's expiration. -Typical usage might look like the following: +Typical usage might look like the following listing: +==== [source,java,indent=0] ---- include::{indexdoc-tests}[tags=expire-repository-demo] ---- <1> We create a `SessionRepository` instance with a generic type, `S`, that extends `Session`. The generic type is defined in our class. -<2> We create a new `Session` using our `SessionRepository` and assign it to a variable of type `S`. +<2> We create a new `Session` by using our `SessionRepository` and assign it to a variable of type `S`. <3> We interact with the `Session`. In our example, we demonstrate updating the amount of time the `Session` can be inactive before it expires. <4> We now save the `Session`. -This is why we needed the generic type `S`. -The `SessionRepository` only allows saving `Session` instances that were created or retrieved using the same `SessionRepository`. -This allows for the `SessionRepository` to make implementation specific optimizations (i.e. only writing attributes that have changed). +This is why we needed the generic type, `S`. +The `SessionRepository` allows saving only `Session` instances that were created or retrieved using the same `SessionRepository`. +This allows for the `SessionRepository` to make implementation specific optimizations (that is, writing only attributes that have changed). The last accessed time is automatically updated when the `Session` is saved. <5> We retrieve the `Session` from the `SessionRepository`. If the `Session` were expired, the result would be null. +==== [[api-sessionrepository]] -=== SessionRepository +=== Using `SessionRepository` A `SessionRepository` is in charge of creating, retrieving, and persisting `Session` instances. -If possible, developers should not interact directly with a `SessionRepository` or a `Session`. -Instead, developers should prefer interacting with `SessionRepository` and `Session` indirectly through the <> and <> integration. +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. [[api-findbyindexnamesessionrepository]] -=== FindByIndexNameSessionRepository +=== Using `FindByIndexNameSessionRepository` Spring Session's most basic API for using a `Session` is the `SessionRepository`. -This API is intentionally very simple, so that it is easy to provide additional implementations with basic functionality. +This API is intentionally very simple, so that you can easily provide additional implementations with basic functionality. -Some `SessionRepository` implementations may choose to implement `FindByIndexNameSessionRepository` also. -For example, Spring's Redis, JDBC and Hazelcast support all implement `FindByIndexNameSessionRepository`. +Some `SessionRepository` implementations may also choose to implement `FindByIndexNameSessionRepository`. +For example, Spring's Redis, JDBC, and Hazelcast support libraries all implement `FindByIndexNameSessionRepository`. The `FindByIndexNameSessionRepository` provides a method to look up all the sessions with a given index name and index value. -As a common use case that is supported by all provided `FindByIndexNameSessionRepository` implementations, there's a convenient method to look up all the sessions for a particular user. -This is done by ensuring that the session attribute with the name `FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME` is populated with the username. -It is the responsibility of the developer to ensure the attribute is populated since Spring Session is not aware of the authentication mechanism being used. -An example of how this might be used can be seen below: +As a common use case that is supported by all provided `FindByIndexNameSessionRepository` implementations, you can use a convenient method to look up all the sessions for a particular user. +This is done by ensuring that the session attribute with the name of `FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME` is populated with the username. +It is your responsibility to ensure that the attribute is populated, since Spring Session is not aware of the authentication mechanism being used. +An example of how to use this can be seen in the following listing: +==== [source,java,indent=0] ---- include::{docs-test-dir}docs/FindByIndexNameSessionRepositoryTests.java[tags=set-username] ---- - -[NOTE] -==== -Some implementations of `FindByIndexNameSessionRepository` will provide hooks to automatically index other session attributes. -For example, many implementations will automatically ensure the current Spring Security user name is indexed with the index name `FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME`. ==== -Once the session is indexed, it can be found using the following: +NOTE: Some implementations of `FindByIndexNameSessionRepository` provide hooks to automatically index other session attributes. +For example, many implementations automatically ensure that the current Spring Security user name is indexed with the index name of `FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME`. +Once the session is indexed, you can find by using code similar to the following: + +==== [source,java,indent=0] ---- include::{docs-test-dir}docs/FindByIndexNameSessionRepositoryTests.java[tags=findby-username] ---- +==== [[api-reactivesessionrepository]] -=== ReactiveSessionRepository +=== Using `ReactiveSessionRepository` A `ReactiveSessionRepository` is in charge of creating, retrieving, and persisting `Session` instances in a non-blocking and reactive manner. -If possible, developers should not interact directly with a `ReactiveSessionRepository` or a `Session`. -Instead, developers should prefer interacting with `ReactiveSessionRepository` and `Session` indirectly through the <> integration. +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. [[api-enablespringhttpsession]] -=== EnableSpringHttpSession +=== Using `@EnableSpringHttpSession` -The `@EnableSpringHttpSession` annotation can be added to an `@Configuration` class to expose the `SessionRepositoryFilter` as a bean named "springSessionRepositoryFilter". -In order to leverage the annotation, a single `SessionRepository` bean must be provided. -For example: +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. +The following example shows how to do so: +==== [source,java,indent=0] ---- include::{docs-test-dir}docs/SpringHttpSessionConfig.java[tags=class] ---- +==== -It is important to note that no infrastructure for session expirations is configured for you out of the box. -This is because things like session expiration are highly implementation dependent. -This means if you require cleaning up expired sessions, you are responsible for cleaning up the expired sessions. +Note that no infrastructure for session expirations is configured for you. +This is because things such as session expiration are highly implementation-dependent. +This means that, if you need to clean up expired sessions, you are responsible for cleaning up the expired sessions. [[api-enablespringwebsession]] -=== EnableSpringWebSession +=== Using `@EnableSpringWebSession` -The `@EnableSpringWebSession` annotation can be added to an `@Configuration` class to expose the `WebSessionManager` as a bean named "webSessionManager". -In order to leverage the annotation, a single `ReactiveSessionRepository` bean must be provided. -For example: +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. +The following example shows how to do so: +==== [source,java,indent=0] ---- include::{docs-test-dir}docs/SpringWebSessionConfig.java[tags=class] ---- +==== -It is important to note that no infrastructure for session expirations is configured for you out of the box. -This is because things like session expiration are highly implementation dependent. -This means if you require cleaning up expired sessions, you are responsible for cleaning up the expired sessions. +Note that no infrastructure for session expirations is configured for you. +This is because things such as session expiration are highly implementation-dependent. +This means that, if you require cleaning up expired sessions, you are responsible for cleaning up the expired sessions. [[api-redisoperationssessionrepository]] -=== RedisOperationsSessionRepository +=== Using `RedisOperationsSessionRepository` -`RedisOperationsSessionRepository` is a `SessionRepository` that is implemented using Spring Data's `RedisOperations`. +`RedisOperationsSessionRepository` 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-redisoperationssessionrepository-new]] -==== Instantiating a RedisOperationsSessionRepository +==== Instantiating a `RedisOperationsSessionRepository` -A typical example of how to create a new instance can be seen below: +You can see a typical example of how to create a new instance in the following listing: +==== [source,java,indent=0] ---- include::{indexdoc-tests}[tags=new-redisoperationssessionrepository] ---- +==== -For additional information on how to create a `RedisConnectionFactory`, refer to the Spring Data Redis Reference. +For additional information on how to create a `RedisConnectionFactory`, see the Spring Data Redis Reference. [[api-redisoperationssessionrepository-config]] -==== EnableRedisHttpSession +==== Using `@EnableRedisHttpSession` In a web environment, the simplest way to create a new `RedisOperationsSessionRepository` is to use `@EnableRedisHttpSession`. -Complete example usage can be found in the <> +You can find complete example usage in the <>. You can use the following attributes to customize the configuration: -* **maxInactiveIntervalInSeconds** - the amount of time before the session will expire in seconds -* **redisNamespace** - allows configuring an application specific namespace for the sessions. Redis keys and channel IDs will start with the prefix of `:`. -* **redisFlushMode** - allows specifying when data will be written to Redis. The default is only when `save` is invoked on `SessionRepository`. -A value of `RedisFlushMode.IMMEDIATE` will write to Redis as soon as possible. +* *maxInactiveIntervalInSeconds*: The amount of time before the session expires, in seconds. +* *redisNamespace*: Allows configuring an application specific namespace for the sessions. Redis keys and channel IDs start with the prefix of `:`. +* *redisFlushMode*: Allows specifying when data is written to Redis. The default is only when `save` is invoked on `SessionRepository`. +A value of `RedisFlushMode.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`. +You can customize the serialization by creating a bean named `springSessionDefaultRedisSerializer` that implements `RedisSerializer`. -==== Redis TaskExecutor +==== Redis `TaskExecutor` -`RedisOperationsSessionRepository` is subscribed to receive events from redis using a `RedisMessageListenerContainer`. -You can customize the way those events are dispatched, by creating a Bean named `springSessionRedisTaskExecutor` and/or a Bean `springSessionRedisSubscriptionExecutor`. -More details on configuring redis task executors can be found https://docs.spring.io/spring-data-redis/docs/{spring-data-redis-version}/reference/html/#redis:pubsub:subscribe:containers[here]. +`RedisOperationsSessionRepository` 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-redisoperationssessionrepository-storage]] ==== Storage Details -The sections below outline how Redis is updated for each operation. -An example of creating a new session can be found below. -The subsequent sections describe the details. +The following sections outline how Redis is updated for each operation. +The following example shows an example of creating a new session: +==== ---- HMSET spring:session:sessions:33fdd1b6-b496-4b33-9f7d-df96679d32fe creationTime 1404360000000 \ maxInactiveInterval 1800 \ @@ -740,14 +789,17 @@ EXPIRE spring:session:sessions:expires:33fdd1b6-b496-4b33-9f7d-df96679d32fe 1800 SADD spring:session:expirations:1439245080000 expires:33fdd1b6-b496-4b33-9f7d-df96679d32fe EXPIRE spring:session:expirations1439245080000 2100 ---- +==== + +The subsequent sections describe the details. ===== Saving a Session -Each session is stored in Redis as a Hash. -Each session is set and updated using the HMSET command. -An example of how each session is stored can be seen below. - +Each session is stored in Redis as a `Hash`. +Each session is set and updated by using the `HMSET` command. +The following example shows how each session is stored: +==== ---- HMSET spring:session:sessions:33fdd1b6-b496-4b33-9f7d-df96679d32fe creationTime 1404360000000 \ maxInactiveInterval 1800 \ @@ -755,141 +807,151 @@ HMSET spring:session:sessions:33fdd1b6-b496-4b33-9f7d-df96679d32fe creationTime sessionAttr:attrName someAttrValue \ sessionAttr2:attrName someAttrValue2 ---- +==== -In this example, the session following statements are true about the session: +In the preceding example, the following statements are true about the session: -* The session ID is 33fdd1b6-b496-4b33-9f7d-df96679d32fe -* The session was created at 1404360000000 in milliseconds since midnight of 1/1/1970 GMT. +* The session ID is 33fdd1b6-b496-4b33-9f7d-df96679d32fe. +* The session was created at 1404360000000 (in milliseconds since midnight of 1/1/1970 GMT). * The session expires in 1800 seconds (30 minutes). -* The session was last accessed at 1404360000000 in milliseconds since midnight of 1/1/1970 GMT. +* The session was last accessed at 1404360000000 (in milliseconds since midnight of 1/1/1970 GMT). * The session has two attributes. -The first is "attrName" with the value of "someAttrValue". -The second session attribute is named "attrName2" with the value of "someAttrValue2". +The first is `attrName`, with a value of `someAttrValue`. +The second session attribute is named `attrName2`, with a value of `someAttrValue2`. [[api-redisoperationssessionrepository-writes]] ===== Optimized Writes -The `Session` instances managed by `RedisOperationsSessionRepository` keeps track of the properties that have changed and only updates those. -This means if an attribute is written once and read many times we only need to write that attribute once. -For example, assume the session attribute "sessionAttr2" from earlier was updated. -The following would be executed upon saving: +The `Session` instances managed by `RedisOperationsSessionRepository` 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. +For example, assume the `sessionAttr2` session attribute from the lsiting in the preceding section was updated. +The following command would be run upon saving: +==== ---- HMSET spring:session:sessions:33fdd1b6-b496-4b33-9f7d-df96679d32fe sessionAttr:attrName2 newValue ---- +==== [[api-redisoperationssessionrepository-expiration]] ===== Session Expiration -An expiration is associated to each session using the EXPIRE command based upon the `Session.getMaxInactiveInterval()`. -For example: +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: +==== ---- EXPIRE spring:session:sessions:33fdd1b6-b496-4b33-9f7d-df96679d32fe 2100 ---- +==== -You will note that the expiration that is set is 5 minutes after the session actually expires. +Note that the expiration that is set to five minutes after the session actually expires. This is necessary so that the value of the session can be accessed when the session expires. -An expiration is set on the session itself five minutes after it actually expires to ensure it is cleaned up, but only after we perform any necessary processing. +An expiration is set on the session itself five minutes after it actually expires to ensure that it is cleaned up, but only after we perform any necessary processing. + +NOTE: The `SessionRepository.findById(String)` method ensures that no expired sessions are returned. +This means that you need not check the expiration before using a session. + +Spring Session relies on the delete and expired https://redis.io/topics/notifications[keyspace notifications] from Redis to fire a <> and a <>, respectively. +`SessionDeletedEvent` or `SessionExpiredEvent` ensure that resources associated with the `Session` are cleaned up. +For example, when you use Spring Session's WebSocket support, the Redis expired or delete event triggers any WebSocket connections associated with the session to be closed. + +Expiration is not tracked directly on the session key itself, since this would mean the session data would no longer be available. Instead, a special session expires key is used. In the preceding example, the expires key is as follows: -[NOTE] ==== -The `SessionRepository.findById(String)` method ensures that no expired sessions will be returned. -This means there is no need to check the expiration before using a session. -==== - -Spring Session relies on the delete and expired https://redis.io/topics/notifications[keyspace notifications] from Redis to fire a <> and <> respectively. -It is the `SessionDeletedEvent` or `SessionExpiredEvent` that ensures resources associated with the Session are cleaned up. -For example, when using Spring Session's WebSocket support the Redis expired or delete event is what triggers any WebSocket connections associated with the session to be closed. - -Expiration is not tracked directly on the session key itself since this would mean the session data would no longer be available. Instead a special session expires key is used. In our example the expires key is: - ---- APPEND spring:session:sessions:expires:33fdd1b6-b496-4b33-9f7d-df96679d32fe "" EXPIRE spring:session:sessions:expires:33fdd1b6-b496-4b33-9f7d-df96679d32fe 1800 ---- +==== -When a session expires key is deleted or expires, the keyspace notification triggers a lookup of the actual session and a SessionDestroyedEvent is fired. +When a session expires key is deleted or expires, the keyspace notification triggers a lookup of the actual session, and a `SessionDestroyedEvent` is fired. -One problem with relying on Redis expiration exclusively is that Redis makes no guarantee of when the expired event will be fired if the key has not been accessed. -Specifically the background task that Redis uses to clean up expired keys is a low priority task and may not trigger the key expiration. -For additional details see https://redis.io/topics/notifications[Timing of expired events] section in the Redis documentation. +One problem with relying on Redis expiration exclusively is that, if the key has not been accessed, Redis makes no guarantee of when the expired event is fired. +Specifically, the background task that Redis uses to clean up expired keys is a low-priority task and may not trigger the key expiration. +For additional details, see the https://redis.io/topics/notifications[Timing of Expired Events] section in the Redis documentation. -To circumvent the fact that expired events are not guaranteed to happen we can ensure that each key is accessed when it is expected to expire. -This means that if the TTL is expired on the key, Redis will remove the key and fire the expired event when we try to access the key. +To circumvent the fact that expired events are not guaranteed to happen, we can ensure that each key is accessed when it is expected to expire. +This means that, if the TTL is expired on the key, Redis removes the key and fires the expired event when we try to access the key. For this reason, each session expiration is also tracked to the nearest minute. -This allows a background task to access the potentially expired sessions to ensure that Redis expired events are fired in a more deterministic fashion. -For example: +This lets a background task access the potentially expired sessions to ensure that Redis expired events are fired in a more deterministic fashion. +The following example shows these events: +==== ---- SADD spring:session:expirations:1439245080000 expires:33fdd1b6-b496-4b33-9f7d-df96679d32fe EXPIRE spring:session:expirations1439245080000 2100 ---- +==== -The background task will then use these mappings to explicitly request each key. +The background task then uses these mappings to explicitly request each key. By accessing the key, rather than deleting it, we ensure that Redis deletes the key for us only if the TTL is expired. -[NOTE] -==== -We do not explicitly delete the keys since in some instances there may be a race condition that incorrectly identifies a key as expired when it is not. -Short of using distributed locks (which would kill our performance) there is no way to ensure the consistency of the expiration mapping. +NOTE: We do not explicitly delete the keys, since, in some instances, there may be a race condition that incorrectly identifies a key as expired when it is not. +Short of using distributed locks (which would kill our performance), there is no way to ensure the consistency of the expiration mapping. By simply accessing the key, we ensure that the key is only removed if the TTL on that key is expired. -==== [[api-redisoperationssessionrepository-sessiondestroyedevent]] -==== SessionDeletedEvent and SessionExpiredEvent +==== `SessionDeletedEvent` and `SessionExpiredEvent` `SessionDeletedEvent` and `SessionExpiredEvent` are both types of `SessionDestroyedEvent`. -`RedisOperationsSessionRepository` supports firing a `SessionDeletedEvent` whenever a `Session` is deleted or a `SessionExpiredEvent` when it expires. +`RedisOperationsSessionRepository` supports firing a `SessionDeletedEvent` when a `Session` is deleted or a `SessionExpiredEvent` when a `Session` expires. This is necessary to ensure resources associated with the `Session` are properly cleaned up. -For example, when integrating with WebSockets the `SessionDestroyedEvent` is in charge of closing any active WebSocket connections. +For example, when integrating with WebSockets, the `SessionDestroyedEvent` is in charge of closing any active WebSocket connections. -Firing `SessionDeletedEvent` or `SessionExpiredEvent` is made available through the `SessionMessageListener` which listens to https://redis.io/topics/notifications[Redis Keyspace events]. +Firing `SessionDeletedEvent` or `SessionExpiredEvent` is made available through the `SessionMessageListener`, which listens to https://redis.io/topics/notifications[Redis Keyspace events]. In order for this to work, Redis Keyspace events for Generic commands and Expired events needs to be enabled. -For example: +The following example shows how to do so: +==== [source,bash] ---- redis-cli config set notify-keyspace-events Egx ---- +==== -If you are using `@EnableRedisHttpSession` the `SessionMessageListener` and enabling the necessary Redis Keyspace events is done automatically. -However, in a secured Redis enviornment the config command is disabled. +If you use `@EnableRedisHttpSession`, managing the `SessionMessageListener` and enabling the necessary Redis Keyspace events is done automatically. +However, in a secured Redis enviornment, the config command is disabled. This means that Spring Session cannot configure Redis Keyspace events for you. -To disable the automatic configuration add `ConfigureRedisAction.NO_OP` as a bean. +To disable the automatic configuration, add `ConfigureRedisAction.NO_OP` as a bean. -For example, Java Configuration can use the following: +For example, with Java configuration, you can use the following: +==== [source,java,indent=0] ---- include::{docs-test-dir}docs/RedisHttpSessionConfigurationNoOpConfigureRedisActionTests.java[tags=configure-redis-action] ---- +==== -XML Configuration can use the following: +In XML configuration, you can use the following: +==== [source,xml,indent=0] ---- include::{docs-test-resources-dir}docs/HttpSessionConfigurationNoOpConfigureRedisActionXmlTests-context.xml[tags=configure-redis-action] ---- +==== [[api-redisoperationssessionrepository-sessioncreatedevent]] -==== SessionCreatedEvent +==== Using `SessionCreatedEvent` -When a session is created an event is sent to Redis with the channel of `spring:session:channel:created:33fdd1b6-b496-4b33-9f7d-df96679d32fe` -such that `33fdd1b6-b496-4b33-9f7d-df96679d32fe` is the session ID. The body of the event will be the session that was created. +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. -If registered as a MessageListener (default), then `RedisOperationsSessionRepository` will then translate the Redis message into a `SessionCreatedEvent`. +If registered as a `MessageListener` (the default), `RedisOperationsSessionRepository` then translates the Redis message into a `SessionCreatedEvent`. [[api-redisoperationssessionrepository-cli]] ==== 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, enter the following into a terminal: +For example, you can enter the following into a terminal: +==== [source,bash] ---- $ redis-cli @@ -900,9 +962,12 @@ redis 127.0.0.1:6379> keys * <1> The suffix of this key is the session identifier of the Spring Session. <2> This key contains all the session IDs that should be deleted at the time `1418772300000`. +==== You can also view the attributes of each session. +The following example shows how to do so: +==== [source,bash] ---- redis 127.0.0.1:6379> hkeys spring:session:sessions:4fc39ce3-63b3-4e17-b1c4-5e1ed96fb021 @@ -913,48 +978,52 @@ redis 127.0.0.1:6379> hkeys spring:session:sessions:4fc39ce3-63b3-4e17-b1c4-5e1e redis 127.0.0.1:6379> hget spring:session:sessions:4fc39ce3-63b3-4e17-b1c4-5e1ed96fb021 sessionAttr:username "\xac\xed\x00\x05t\x00\x03rob" ---- +==== [[api-reactiveredisoperationssessionrepository]] -=== ReactiveRedisOperationsSessionRepository +=== Using `ReactiveRedisOperationsSessionRepository` -`ReactiveRedisOperationsSessionRepository` is a `ReactiveSessionRepository` that is implemented using Spring Data's `ReactiveRedisOperations`. +`ReactiveRedisOperationsSessionRepository` 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-reactiveredisoperationssessionrepository-new]] -==== Instantiating a ReactiveRedisOperationsSessionRepository +==== Instantiating a `ReactiveRedisOperationsSessionRepository` -A typical example of how to create a new instance can be seen below: +The following example shows how to create a new instance: +==== [source,java,indent=0] ---- include::{indexdoc-tests}[tags=new-reactiveredisoperationssessionrepository] ---- +==== -For additional information on how to create a `ReactiveRedisConnectionFactory`, refer to the Spring Data Redis Reference. +For additional information on how to create a `ReactiveRedisConnectionFactory`, see the Spring Data Redis Reference. [[api-reactiveredisoperationssessionrepository-config]] -==== EnableRedisWebSession +==== Using `@EnableRedisWebSession` In a web environment, the simplest way to create a new `ReactiveRedisOperationsSessionRepository` is to use `@EnableRedisWebSession`. You can use the following attributes to customize the configuration: -* **maxInactiveIntervalInSeconds** - the amount of time before the session will expire in seconds -* **redisNamespace** - allows configuring an application specific namespace for the sessions. Redis keys and channel IDs will start with the prefix of `:`. -* **redisFlushMode** - allows specifying when data will be written to Redis. The default is only when `save` is invoked on `ReactiveSessionRepository`. -A value of `RedisFlushMode.IMMEDIATE` will write to Redis as soon as possible. +* *maxInactiveIntervalInSeconds*: The amount of time before the session expires, in seconds +* *redisNamespace*: Allows configuring an application specific namespace for the sessions. Redis keys and channel IDs start with q prefix of `:`. +* *redisFlushMode*: Allows specifying when data is written to Redis. The default is only when `save` is invoked on `ReactiveSessionRepository`. +A value of `RedisFlushMode.IMMEDIATE` writes to Redis as soon as possible. [[api-reactiveredisoperationssessionrepository-writes]] ===== Optimized Writes -The `Session` instances managed by `ReactiveRedisOperationsSessionRepository` keeps track of the properties that have changed and only updates those. -This means if an attribute is written once and read many times we only need to write that attribute once. +The `Session` instances managed by `ReactiveRedisOperationsSessionRepository` 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-reactiveredisoperationssessionrepository-cli]] ==== 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, enter the following into a terminal: +For example, you can enter the following command into a terminal window: +==== [source,bash] ---- $ redis-cli @@ -963,9 +1032,12 @@ redis 127.0.0.1:6379> keys * ---- <1> The suffix of this key is the session identifier of the Spring Session. +==== -You can also view the attributes of each session. +You can also view the attributes of each session by using the `hkeys` command. +The following example shows how to do so: +==== [source,bash] ---- redis 127.0.0.1:6379> hkeys spring:session:sessions:4fc39ce3-63b3-4e17-b1c4-5e1ed96fb021 @@ -976,249 +1048,271 @@ redis 127.0.0.1:6379> hkeys spring:session:sessions:4fc39ce3-63b3-4e17-b1c4-5e1e redis 127.0.0.1:6379> hget spring:session:sessions:4fc39ce3-63b3-4e17-b1c4-5e1ed96fb021 sessionAttr:username "\xac\xed\x00\x05t\x00\x03rob" ---- +==== [[api-mapsessionrepository]] -=== 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`. -The implementation can be used with a `ConcurrentHashMap` as a testing or convenience mechanism. -Alternatively, it can be used with distributed `Map` implementations. For example, it can be used with Hazelcast. +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` -Creating a new instance is as simple as: +The following example shows how to create a new instance: +==== [source,java,indent=0] ---- include::{indexdoc-tests}[tags=new-mapsessionrepository] ---- +==== [[api-mapsessionrepository-hazelcast]] ==== Using Spring Session and Hazlecast -The <> is a complete application demonstrating using Spring Session with Hazelcast. +The <> is a complete application that demonstrates how to use Spring Session with Hazelcast. -To run it use the following: +To run it, use the following command: +==== +---- ./gradlew :samples:hazelcast:tomcatRun +---- +==== -The <> is a complete application demonstrating using Spring Session with Hazelcast and Spring Security. +The <> 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`. +It includes example Hazelcast `MapListener` implementations that support firing `SessionCreatedEvent`, `SessionDeletedEvent`, and `SessionExpiredEvent`. -To run it use the following: +To run it, use the following command: +==== +---- ./gradlew :samples:hazelcast-spring:tomcatRun +---- +==== [[api-reactivemapsessionrepository]] -=== 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`. -The implementation can be used with a `ConcurrentHashMap` as a testing or convenience mechanism. -Alternatively, it can be used with distributed `Map` implementations with the requirement that the supplied `Map` must be a non-blocking. +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-jdbcoperationssessionrepository]] -=== JdbcOperationsSessionRepository +=== Using `JdbcOperationsSessionRepository` `JdbcOperationsSessionRepository` 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`. -Please note that this implementation does not support publishing of session events. +Note that this implementation does not support publishing of session events. [[api-jdbcoperationssessionrepository-new]] -==== Instantiating a JdbcOperationsSessionRepository +==== Instantiating a `JdbcOperationsSessionRepository` -A typical example of how to create a new instance can be seen below: +The following example shows how to create a new instance: +==== [source,java,indent=0] ---- include::{indexdoc-tests}[tags=new-jdbcoperationssessionrepository] ---- +==== -For additional information on how to create and configure `JdbcTemplate` and `PlatformTransactionManager`, refer to the https://docs.spring.io/spring/docs/{spring-framework-version}/spring-framework-reference/data-access.html[Spring Framework Reference Documentation]. +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-jdbcoperationssessionrepository-config]] -==== EnableJdbcHttpSession +==== Using `@EnableJdbcHttpSession` In a web environment, the simplest way to create a new `JdbcOperationsSessionRepository` is to use `@EnableJdbcHttpSession`. -Complete example usage can be found in the <> +You can find complete example usage in the <> 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 +* *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 -===== Custom LobHandler +===== Customizing `LobHandler` -You can customize the BLOB handling by creating a Bean named `springSessionLobHandler` that implements `LobHandler`. +You can customize BLOB handling by creating a bean named `springSessionLobHandler` that implements `LobHandler`. -===== Custom 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`) will be automatically picked up and used for serialization and deserialization. -However, you can override the default `ConversionService` by providing a Bean named `springSessionConversionService`. +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-jdbcoperationssessionrepository-storage]] ==== Storage Details By default, this implementation uses `SPRING_SESSION` and `SPRING_SESSION_ATTRIBUTES` tables to store sessions. -Note that the table name can be easily customized as already described. In that case the table used to store attributes will be named using the provided table name, suffixed with `_ATTRIBUTES`. -If further customizations are needed, SQL queries used by the repository can be customized using `set*Query` setter methods. In this case you need to manually configure the `sessionRepository` bean. +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`. +If further customizations are needed, you can customize the SQL queries used by the repository by using `set*Query` setter methods. In this case, you need to manually configure the `sessionRepository` bean. -Due to the differences between the various database vendors, especially when it comes to storing binary data, make sure to use SQL script specific to your database. +Due to the differences between the various database vendors, especially when it comes to storing binary data, make sure to use SQL scripts specific to your database. Scripts for most major database vendors are packaged as `org/springframework/session/jdbc/schema-\*.sql`, where `*` is the target database type. -For example, with PostgreSQL database you would use the following schema script: +For example, with PostgreSQL, you can use the following schema script: +==== [source,sql,indent=0] ---- include::{session-jdbc-main-resources-dir}org/springframework/session/jdbc/schema-postgresql.sql[] ---- +==== -And with MySQL database: +With MySQL database, you can use the following script: +==== [source,sql,indent=0] ---- include::{session-jdbc-main-resources-dir}org/springframework/session/jdbc/schema-mysql.sql[] ---- +==== -==== Transaction management +==== Transaction Management All JDBC operations in `JdbcOperationsSessionRepository` are executed in a transactional manner. -Transactions are executed with propagation set to `REQUIRES_NEW` in order to avoid unexpected behavior due to interference with existing transactions (for example, executing `save` operation in a thread that already participates in a read-only transaction). +Transactions are executed 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-hazelcastsessionrepository]] -=== HazelcastSessionRepository +=== Using `HazelcastSessionRepository` `HazelcastSessionRepository` 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-hazelcastsessionrepository-new]] -==== Instantiating a HazelcastSessionRepository +==== Instantiating a `HazelcastSessionRepository` -A typical example of how to create a new instance can be seen below: +The following example shows how to create a new instance: +==== [source,java,indent=0] ---- include::{indexdoc-tests}[tags=new-hazelcastsessionrepository] ---- +==== -For additional information on how to create and configure Hazelcast instance, refer to the http://docs.hazelcast.org/docs/{hazelcast-version}/manual/html-single/index.html#hazelcast-configuration[Hazelcast documentation]. +For additional information on how to create and configure Hazelcast instance, see the http://docs.hazelcast.org/docs/{hazelcast-version}/manual/html-single/index.html#hazelcast-configuration[Hazelcast documentation]. [[api-enablehazelcasthttpsession]] -==== EnableHazelcastHttpSession +==== Using `@EnableHazelcastHttpSession` -If you wish to use https://hazelcast.org/[Hazelcast] as your backing source for the `SessionRepository`, then the `@EnableHazelcastHttpSession` annotation -can be added to an `@Configuration` class. This extends the functionality provided by the `@EnableSpringHttpSession` annotation but makes the `SessionRepository` for you in Hazelcast. +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. -Complete configuration example can be found in the <> +You can find a complete configuration example in the <>. [[api-enablehazelcasthttpsession-customize]] ==== Basic Customization You can use the following attributes on `@EnableHazelcastHttpSession` to customize the configuration: -* **maxInactiveIntervalInSeconds** - the amount of time before the session will expire in seconds. Default is 1800 seconds (30 minutes) -* **sessionMapName** - the name of the distributed `Map` that will be used in Hazelcast to store the session data. +* *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 -Using a `MapListener` to respond to entries being added, evicted, and removed from the distributed `Map`, these events will trigger -publishing `SessionCreatedEvent`, `SessionExpiredEvent`, and `SessionDeletedEvent` events respectively using the `ApplicationEventPublisher`. + +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 -Sessions will be stored in a distributed `IMap` in Hazelcast. -The `IMap` interface methods will be used to `get()` and `put()` Sessions. -Additionally, `values()` method is used to support `FindByIndexNameSessionRepository#findByIndexNameAndIndexValue` operation, together with appropriate `ValueExtractor` that needs to be registered with Hazelcast. Refer to <> 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 will be automatically removed from the `IMap`. +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. +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 shouldn't need to configure any settings such as `max-idle-seconds` or `time-to-live-seconds` for the `IMap` within the Hazelcast configuration. +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. -Note that if you use Hazelcast's `MapStore` to persist your sessions `IMap` there are some limitations when reloading the sessions from `MapStore`: +Note that if you use Hazelcast's `MapStore` to persist your sessions `IMap`, the following limitations apply when reloading the sessions from `MapStore`: -* reload triggers `EntryAddedListener` which results in `SessionCreatedEvent` being re-published -* reload uses default TTL for a given `IMap` which results in sessions losing their original TTL +* Reloading triggers `EntryAddedListener` results in `SessionCreatedEvent` being re-published +* Reloading uses default TTL for a given `IMap` results in sessions losing their original TTL [[custom-sessionrepository]] -== Custom SessionRepository +== Customing `SessionRepository` Implementing a custom <> API should be a fairly straightforward task. -Coupling the custom implementation with <> support allow to easily reuse existing Spring Session configuration facilities and infrastructure. -There are however a couple of aspects that deserve a closer consideration. +Coupling the custom implementation with <> support lets you reuse existing Spring Session configuration facilities and infrastructure. +There are, however, a couple of aspects that deserve closer consideration. -During a lifecycle of an HTTP request, the `HttpSession` is typically is persisted to `SessionRepository` twice. -First to ensure that the session is available to the clients as soon as the client has access to the session ID, and it is also necessary to write after the session is committed because further modifications to the session might be made. -Having this in mind, it is generally recommended for a `SessionRepository` implementation to keep track of changes to ensure that only deltas are saved. -This is in particular very important in highly concurrent environments, where multiple requests operate on the same `HttpSession` and therefore cause race conditions, with requests overriding each others changes to session attributes. -All of the `SessionRepository` implementations provided by Spring Session use the described approach to persisting session changes and can be used for guidance while implementing custom `SessionRepository`. +During the lifecycle of an HTTP request, the `HttpSession` is typically persisted to `SessionRepository` twice. +The first persist operation is to ensure that the session is available to the client as soon as the client has access to the session ID, and it is also necessary to write after the session is committed because further modifications to the session might be made. +Having this in mind, we generally recommend that a `SessionRepository` implementation keep track of changes to ensure that only deltas are saved. +This is particularly important in highly concurrent environments, where multiple requests operate on the same `HttpSession` and, therefore, cause race conditions, with requests overriding each other's changes to session attributes. +All of the `SessionRepository` implementations provided by Spring Session use the described approach to persist session changes and can be used for guidance when you implement custom `SessionRepository`. Note that the same recommendations apply for implementing a custom <> as well. -Of course, in this case the <> should be used. +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. +The focus of these changes is to improve and harmonize Spring Session's APIs as well as remove the deprecated components. -=== Baseline update +=== 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. -Refer to guide for https://github.com/spring-projects/spring-framework/wiki/Upgrading-to-Spring-Framework-5.x[Upgrading to Spring Framework 5.x] for reference on upgrading Spring Framework. +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 split the modules, the existing `spring-session` has been replaced with `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 appropriate `SessionRepository` and functionality related to that data store. -This applies to several existing that were previously a simple dependency aggregator helper modules but with new module arrangement actually carry the implementation: +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: +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 will continue to be available albeit under a changed artifact names: +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 +=== Replaced and Removed Packages, Classes, and Methods -* `ExpiringSession` API has been merged into `Session` API -* `Session` API has been enhanced to make full use of Java 8 -* `Session` API has been extended with `changeSessionId` support -* `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 -* Redis namespace used by `RedisOperationsSessionRepository` is now fully configurable, instead of being partial 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 +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 it's alignment to the counterpart from the reactive world, the support for managing multiple users' sessions in a single browser instance has been removed. +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. -Please find additional information below. +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[StackOverflow with the tag spring-session]. -Similarly we encourage helping others by answering questions on StackOverflow. +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 -Our source code can be found on GitHub at https://github.com/spring-projects/spring-session/ +You can find the source code on GitHub at https://github.com/spring-projects/spring-session/ [[community-issues]] === Issue Tracking @@ -1228,7 +1322,7 @@ We track issues in GitHub issues at https://github.com/spring-projects/spring-se [[community-contributing]] === Contributing -We appreciate https://help.github.com/articles/using-pull-requests/[Pull Requests]. +We appreciate https://help.github.com/articles/using-pull-requests/[pull requests]. [[community-license]] === License @@ -1254,14 +1348,11 @@ Spring Session is Open Source software released under the https://www.apache.org The minimum requirements for Spring Session are: -* Java 8+ -* If you are running in a Servlet Container (not required), Servlet 3.1+ -* If you are using other Spring libraries (not required), the minimum required version is Spring 5.0.x. +* 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 only has a required dependency on `spring-jcl`. -For an example of using Spring Session without any other Spring dependencies, refer to the <> application. -==== +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.