Spring Session Documentation

repository·main·Indexed 24 days ago

https://github.com/spring-projects/spring-session

Spring Session provides an API and implementations for managing user session information, enabling clustered sessions independent of the application container. It includes support for HttpSession and WebSession, with specialized modules for storage via Redis and JDBC. Key features include the SessionRepository and ReactiveSessionRepository APIs, custom CookieSerializer implementations, and configuration options via annotations like @EnableRedisHttpSession and @EnableJdbcHttpSession.

Tokens
21K
Snippets
43
Records
115
Agent score
83%

What's inside Spring Session

  1. Overview of Spring Session capabilities

    main

    Spring Session provides an API and implementations for managing user session information. It enables support for clustered sessions without being tied to a specific application container solution.

    Key integration features include:

    • HttpSession: Replaces the standard HttpSession in application containers (like Tomcat) in a container-neutral way. It supports providing session IDs in headers, which is useful for RESTful APIs.
    • WebSocket: Keeps the HttpSession alive when receiving WebSocket messages.
    • WebSession: Replaces Spring WebFlux's WebSession in a container-neutral way.
  2. What is Spring Session and what problem does it solve?

    main

    Spring Session provides an API and implementations for managing a user's session information. It solves the problem of session management in distributed environments where traditional in-memory sessions (stored in a single server's memory) prevent other application instances from accessing session data.

    By providing a layer of abstraction between the application and the session management, Spring Session allows session data to be stored in various shared persistent stores (such as relational databases or NoSQL databases like Redis). This enables:

    • Distributed web applications: Multiple servers can access and update the same session data in a shared store.
    • Session scalability: Reduces the risk of out-of-memory errors by moving session storage out of the application server's memory.
    • Session backup and recovery: Provides a mechanism to recover session data in case of server failure or downtime.
  3. How WebSocket messages affect session activity

    main

    When using Spring Session with WebSockets, the session lifecycle is tied to user activity via messages:

    • Keeping the session alive: Sending messages from a user (inbound messages) updates the session's last accessed time, preventing expiration.
    • Session expiration: If no messages are sent for the duration of the timeout, the session expires, and the WebSocketRegistryListener will close the associated WebSocket connections.
    • Important Limitation: Only messages sent from a user keep the session alive. Received messages (outbound) do not imply user activity and will not renew the session expiration.
  4. How Spring Session and Spring Security work together

    main

    Spring Session replaces the standard Servlet Container HttpSession (e.g., Tomcat's implementation) with a custom implementation backed by a data store like Redis.

    When Spring Security's SecurityContextPersistenceFilter saves the SecurityContext to the HttpSession, the data is persisted into Redis. On the client side, Spring Session creates a cookie (default name SESSION) containing the session ID. This allows session state to be shared across multiple application instances or survive server restarts.

  5. Integrate Spring Session with HttpSession

    main

    Spring Session provides transparent integration with the standard HttpSession interface. This allows you to switch from container-managed sessions to Spring Session-backed implementations (like Redis or JDBC) without changing your application code.

    Key benefits include:

    • Clustered Sessions: Easily support clustered environments using backends like Redis without being tied to a specific application container.
    • RESTful APIs: Support providing session IDs via HTTP headers instead of just cookies.
  6. Why use Spring Session with WebSockets?

    main

    By default, the WebSocket specification (JSR-356) can cause issues with session management. If an HttpSession times out, any WebSocket associated with that session and an authenticated user may be forcibly closed. This leads to poor user experiences, such as being disconnected from a chat application simply because the user was not making active HTTP requests.

    Spring Session provides transparent integration with Spring's WebSocket support to prevent these premature disconnections and ensure that active WebSocket communication can help maintain the user's session state.

  7. Using the `Session` API

    main

    A Session acts as a simplified Map of name-value pairs. When using a SessionRepository, you should use a generic type S that extends Session to allow the repository to perform implementation-specific optimizations, such as writing only changed attributes.

    Key behaviors:

    • Saving: You must save the session back to the repository after interacting with it. The repository only allows saving instances created or retrieved by that specific repository instance.
    • Expiration: The Session API provides methods to manage expiration. The last accessed time is automatically updated when the session is saved.
    • Retrieval: If a session has expired, attempting to retrieve it from the repository will return null.
  8. How WebSession integration works under the hood

    main

    Spring Session integrates with Spring WebFlux by leveraging the WebSessionStore API.

    1. Custom WebSession: Spring Session uses a SpringSessionWebSession implementation that delegates operations to a Spring Session Session object. This implementation handles lifecycle states like NEW and STARTED, and provides methods like changeSessionId().
    2. Custom WebSessionStore: A SpringSessionWebSessionStore is created which implements WebSessionStore. It delegates to a ReactiveSessionRepository and wraps the underlying Session into the SpringSessionWebSession implementation.
    3. Registration: For Spring WebFlux to detect and use this custom store, the WebSessionStore must be registered in the ApplicationContext as a bean named webSessionManager.
  9. Using `FindByIndexNameSessionRepository` to look up sessions by user

    main

    Some SessionRepository implementations (like Redis and JDBC) also implement FindByIndexNameSessionRepository. This allows you to look up all sessions associated with a specific index value, such as a username.

    To use this, you must ensure that the session attribute named FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME is populated with the username. Spring Session does not automatically populate this; you must do so based on your authentication mechanism.

    Once indexed, you can use the repository to find all sessions for a particular user.

  10. How Spring Session's HttpSession integration works

    main

    Spring Session achieves transparent integration by wrapping the standard HttpServletRequest and HttpSession interfaces.

    1. Request Wrapping: A SessionRepositoryRequestWrapper (extending HttpServletRequestWrapper) is created. This wrapper overrides getSession() and getSession(boolean createNew) to return a custom HttpSession implementation provided by Spring Session.
    2. Filter Injection: A SessionRepositoryFilter is placed early in the servlet filter chain. It wraps the original HttpServletRequest with the SessionRepositoryRequestWrapper and passes it down the FilterChain.

    Critical Requirement: The SessionRepositoryFilter must be placed before any other component or filter that interacts with the HttpSession to ensure the wrapped request is used.

  11. How Spring Session Redis works

    main

    When using Spring Session with Redis:

    1. Session Storage: Instead of storing session attributes in the Servlet Container's memory, they are persisted in Redis.
    2. Session Tracking: Spring Session creates a cookie named SESSION in the browser containing the session ID.
    3. Transparency: The application interacts with the standard HttpSession API, but the underlying implementation is managed by Spring Session.

    To manually clear sessions in Redis, you can use redis-cli to delete keys matching the pattern spring:session:sessions:*.

  12. How Spring Session JDBC works with Spring Boot

    main

    Spring Session works by replacing the standard HttpSession implementation with a custom one backed by a relational database.

    1. Filter Injection: Spring Boot creates a springSessionRepositoryFilter bean (implementing Filter). This filter is responsible for replacing the HttpSession for every request.
    2. Persistence: When components like Spring Security's SecurityContextPersistenceFilter save data to the HttpSession, that data is persisted into the configured database (e.g., H2, MySQL, PostgreSQL).
    3. Session Tracking: When a new session is created, Spring Session issues a cookie named SESSION to the browser containing the session ID.