Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do relational database-based HTTP Session Persistence in Spring 4?

I need to be able to store the HTTP Session in a relational database in order to do stateless load balancing of my front-end users across multiple front-end servers. How can I achieve this in Spring 4?

I see how one can do this with Redis, however there does not appear to be documentation on how to do this with a relational database e.g. Postgres.

like image 838
BestPractices Avatar asked Jul 14 '15 01:07

BestPractices


People also ask

How session is maintained in spring?

By default, Spring Security will create a session when it needs one — this is “ifRequired“. For a more stateless application, the “never” option will ensure that Spring Security itself won't create any session. But if the application creates one, Spring Security will make use of it.

What is SessionCreationPolicy?

Enum SessionCreationPolicySpecifies the various session creation policies for Spring Security.


1 Answers

With Spring Session (it transparently will override HttpSessions from Java EE) you can just take SessionRepository interface and implement it with your custom ex. JdbcSessionRepository. It is kind of easy to do. When you have your implementation, then just add manually (you don't need @EnableRedisHttpSession annotation) created filter to filter chain, like bellow:

@Configuration
@EnableWebMvcSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

   //other stuff...

   @Autowired
   private SessionRepository<ExpiringSession> sessionRepository;

   private HttpSessionStrategy httpSessionStrategy = new CookieHttpSessionStrategy(); // or HeaderHttpSessionStrategy

   @Bean
   public SessionRepository<ExpiringSession> sessionRepository() {
       return new JdbcSessionRepository();
   }

   @Override
   protected void configure(HttpSecurity http) throws Exception {
       super.configure(http);
       SessionRepositoryFilter<ExpiringSession> sessionRepositoryFilter = new SessionRepositoryFilter<>(sessionRepository);
       sessionRepositoryFilter.setHttpSessionStrategy(httpSessionStrategy);
       http
            .addFilterBefore(sessionRepositoryFilter, ChannelProcessingFilter.class);
   }
}

Here you have how SessionRepository interface looks like. It has only 4 methods to implement. For how to create Session object, you can look in MapSessionRepository and MapSession implementation (or RedisOperationsSessionRepository and RedisSession).

public interface SessionRepository<S extends Session> {
   S createSession();
   void save(S session);
   S getSession(String id);
   void delete(String id);
}

Example solution https://github.com/Mati20041/spring-session-jpa-repository

like image 179
Mati Avatar answered Nov 01 '22 15:11

Mati