Spring security invalid session redirect

josete picture josete · May 26, 2015 · Viewed 14.7k times · Source

I'm using spring security 4.0.1 inside a spring boot 1.2.3 web application ( and also with spring-session 1.0.1, but this is irrelevant for the case ).

I do have a private area, and an all access area ( "/about", "/","/contact",... more than 20 pages ) for which every user can access. ( it's like a web-shop )

Whenever a logged-in user session expires,Spring detects an invalid session and redirects the user to the '.invalidSessionUrl("/session/error/invalid")'

However, i only want to be redirected if the target link in inside the private area, nor the public one.

How can i avoid that ?

Thanks.

This is my (java) config : ( updated after seen post )

 http
            .authorizeRequests()
            .anyRequest()
                .permitAll()
            .antMatchers("/privado/**")
                .authenticated()
            .and()
                .formLogin()
                .loginPage("/login")
                .failureUrl("/login?error")
                .defaultSuccessUrl("/")
                .successHandler(new SessionSuccessHandler())
            .and()
                .logout()
                .logoutSuccessUrl("/")
                .deleteCookies("JSESSIONID", "SESSION")
            .and()
                .sessionManagement()
                .invalidSessionUrl("/session/error/invalid")
            .sessionFixation()
            .changeSessionId()
            .maximumSessions(1)
            .expiredUrl("/session/error/expired")
            .and()
            .and()
                .csrf()
                .ignoringAntMatchers("/jolokia/**", "/v1.0/**");

How can i achieve that ?

Thanks a lot.

Answer

Dayo picture Dayo · Aug 18, 2016

@RobWinch - This seem like a pretty common use case and the solution you propose does not seem to work from the test I ran and also comments. Similar issue was raised I believe in http://forum.spring.io/forum/spring-projects/security/94772-redirect-to-invalid-session-url-only-when-user-accesses-secured-resource and it appears it was never resolved. My thinking is to have multiple http settings (using xml config)

<http pattern="/aboutUs**" security="none" />
<http pattern="/contact**" security="none" />
etc

This does not seem ideal when having quite a number unsecured pages and also adding a new unsecured page requires a configuration update. It will be nice if we can have an "ideal" solution for this use case. With Spring security 4.1 release, it appears there is still no clear way to do this.