简体   繁体   中英

Why spring security logout does not work?

I have a problem with spring security, I try to logout in spring security,but it seem does not work.I request the logout url, but the session and auth does not clear.

This is for a spring cloud application, running spring cloud Finchley.RELEASE.Use zuul,spring security and oauth2.

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/login","/login.html").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            .successHandler(loginSuccessHandler)
            .failureHandler(loginFailHandler)
            .permitAll()
            .and()
            .logout()
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .logoutSuccessHandler(logoutHandler)
            .clearAuthentication(true)
            .deleteCookies("JSESSIONID")
            .invalidateHttpSession(true);

    http .cors().and().csrf().disable();

}

I expect after request logout url,the authentication and session is invalid

Use below code in your logoutHandler.

@Service
@Scope(scopeName = BeanDefinition.SCOPE_SINGLETON)
@Transactional(readOnly=false)
public class CustomLogoutSuccessHandler implements LogoutSuccessHandler{

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest,
            HttpServletResponse httpServletResponse, Authentication authentication)
            throws IOException, ServletException {
        if (authentication != null && authentication.getDetails() != null) {
            try {
                httpServletRequest.getSession().invalidate();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        httpServletResponse.sendRedirect("/");
    }
}

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