Is it possible to have two session management strategies for different apis based on ant matcher

I was trying out the following config code, to get different session management for two APIs based on ant matchers

 http  .authorizeRequests().antMatchers("/apiV1/**").authenticated()  .and().sessionManagement()  .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)   // How to add in details for custom session cookie for apiV1 ?  .and().authorizeRequests().antMatchers("/apiV2/**").authenticated()  .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)   // How to add in details for custom session cookie for apiV2 ?  .and().oauth2Login(Customizer.withDefaults()); 

I would also require to invalidate /apiV2 session after 3 minutes (configurable).

Also is it possible to maintain two different session cookie attributes (with custom names) for these two APIs and have code to invalidate them based on some business logic?

Add Comment
1 Answer(s)

You can do this by having separate filter chains to handle each request. Implement 2 separate config classes that extend the WebSecurityConfigurerAdapter

Have one with:  @Configuration @Order(1) public class SecurityConfig1 extends WebSecurityConfigurerAdapter{      protected void configure(HttpSecurity http) throws Exception {             http.requestMatcher(""/apiV1/**"")     .... // 

and

@Configuration @Order(2) public class SecurityConfig2 extends WebSecurityConfigurerAdapter{      protected void configure(HttpSecurity http) throws Exception {             http.requestMatcher(""/apiV2/**"")     .... 

Spring will create 2 seperate filter chains, and the Filter chain proxy will route requests to each one based on the request matcher, then you can customize the Session fitlers etc in each one, and even have different authentication etc.

More info in this article: https://www.baeldung.com/spring-security-multiple-entry-points

Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.