简体   繁体   中英

Spring security auto redirect to login page after session timeout

I need to redirect automatically to login page after session timeout or at least show alert that session is expired, I tried to configure Spring Security, but it is not working,debugger don't catch code in LogoutSuccessHandlerService after timeout. Maybe I missed something or this approach with Spring Security is wrong from the start? If it is so, can somebody provide full working example of such task? I am using Spring Boot 2.5.6, Spring Security, front-end is html, javascript, JQuery and dataTable. Here is my code:

SecurityConfig.java

private final AppProperties appProperties;

@Autowired
private LogoutSuccessHandlerService logoutSuccessHandlerService;

@Override
public void configure(WebSecurity web) {
    web.ignoring()
            .antMatchers("/static/**")
            .antMatchers("/webjars/**")
            .antMatchers("/css/**")
            .antMatchers("/fonts/**")
            .antMatchers("/img/**")
            .antMatchers("/js/**")
            .antMatchers("/scripts/**")
    ;
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .formLogin()
            .loginPage("/login")
            .permitAll()
            .defaultSuccessUrl("/", true)
            .failureUrl("/login?error=true")
            .loginProcessingUrl("/j_spring_security_check")
            .and()
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .logout()
            .invalidateHttpSession(true)
            .logoutSuccessHandler(logoutSuccessHandlerService)
            .logoutSuccessUrl("/login")
            .permitAll()
            .and()
            .csrf().disable();
}


@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    AppProperties.Security security = appProperties.getSecurity();

    auth.inMemoryAuthentication()
            .withUser(security.getUser())
            .password(passwordEncoder().encode(security.getPassword()))
            .roles(security.getRole());
}

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

LogoutSuccessHandlerService.java extends SimpleUrlLogoutSuccessHandler

@Override
public void onLogoutSuccess(HttpServletRequest request,
                            HttpServletResponse response,
                            Authentication authentication) throws IOException, ServletException {
    if (authentication != null) {

    }
    log.info("logout success");
    setDefaultTargetUrl("/login");
    
    super.onLogoutSuccess(request, response, authentication);
}

application-local.yml

server: port: 8086 servlet: session: timeout: 2m

Found a solution. Spring security is unable to solve it, I used JavaScript. This solution sends request every minute and if response data is not null, redirect occurs. It works only with one logged in user in browser.

Header html page

<script>
            setInterval(function() {
                $.ajax({
                    url: "/check-session",
                    method: "GET",
                    contentType: 'application/json; charset=utf-8',
                    success: function(data){
                        if (data && data.length > 0) {
                            window.location.replace("/login");
                        }
                    },
                    error: function (data) {
                        console.log("error");
                        console.log(data);
                    }
                })
            }, 60000);
    </script>

LoginController

@GetMapping("/check-session")
public ResponseEntity<String> checkSession() {
    return new ResponseEntity<>(HttpStatus.OK);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM