mardi 30 juin 2020

Spring Session expired - Get / Post behaves differently

I have a Spring boot 2.1.x web application with session configured to be expired after X minutes. I have an expired session page which I want to take users to when session expires. To do that, I use the following codes.

Spring security config:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  // some other code
 
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .anyRequest()
        .permitAll()
        .and()
        .sessionManagement()
        .invalidSessionStrategy(new MyInvalidSessionStrategy());
  }
  
  private static class MyInvalidSessionStrategy implements InvalidSessionStrategy {
    @Override
    public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
      if (request.getSession(false) == null) { // IMPORTANT: retrieve session
        request.getSession(true);
        response.sendRedirect("/"); // home page
      } else {
        response.sendRedirect(Mappings.URL_EXPIRED_SESSION); // expired session page
      }
    }
  }
}

When a session expires, a user can have 2 possible actions: (i) Refresh current page (or Back button) and ii) Submit a form on current page

For the i) situation, user's action causes a GET request and the session is returned as null and user is taken to home page.

For the ii) situation, user's action causes a POST request and the session is found (although expired) and user is taken to the expired page.

My question is why it is behaving this way. i.e. why session is null when GET.




Aucun commentaire:

Enregistrer un commentaire