Java – spring security returns 302 when attempting to log out
I use spring security (4.0.2. Release) to protect my application
I can log in normally and my authenticated URL is protected, but when I try to log out, I will continue to get 302 post response, and then redirect to my configured failureurl ("/ CMS / login? Error")
This is my websecurityconfig class
@Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/*").permitAll() .antMatchers("/cms/*").authenticated() .antMatchers("/cms/*/*").authenticated() .antMatchers("/cms/*/*/*").authenticated().and() .formLogin() .loginPage("/cms/login") .defaultSuccessUrl("/cms/login?success") .failureUrl("/cms/login?error") .permitAll().and() .logout() .logoutUrl("/cms/login?logout") .logoutSuccessUrl("/cms/login") .permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("u") .password("p") .roles("USER"); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
This is my login controller:
@Slf4j @Controller @RequestMapping(value = {"/cms","/cms/login"}) public class CmsLoginController extends CmsBaseController { @RequestMapping public ModelAndView handleLogin(HttpServletResponse request,Model model,@RequestParam(value = LOGIN_SUCCESS,required = false) String success,@RequestParam(value = LOGIN_ERROR,required = false) String error,@RequestParam(value = logoUT,required = false) String logout) { try { if (success != null) { setLoggedIn(true); request.sendRedirect(XXXXX); } if (error != null) { model.addAttribute(LOGIN_ERROR,"Invalid username and password!"); } if (logout != null) { model.addAttribute(logoUT,"You've been logged out successfully."); setLoggedIn(false); } return new ModelAndView(CMS_CONTEXT + LOGIN_URL); } catch(Exception e) { setLoggedIn(false); log.error(e.toString(),e); return new ModelAndView(ERROR_VIEW_NAME); } } }
In order to record, I initially got the logout function normal, but I have to introduce some unfortunate changes that destroy it
Any ideas? thank you
Solution
I think the problem is the CSRF filter In spring security 4, CSRF prevention is enabled by default, and each post request requires a CSRF token
If you migrate code from a previous version of spring, you are likely to have problems
To quickly test, add http.com to the configuration csrf(). disable. If it works in this way, turn back to CSRF protection and add the CSRF token to the post logout request in some way