为什么Spring Security注销不起作用?

时间:2019-08-12 10:57:12

标签: java spring-security spring-security-oauth2

我在Spring Security中遇到问题,我尝试在Spring Security中注销,但似乎不起作用。我请求注销URL,但会话和身份验证未清除。

这是用于运行Spring Cloud Finchley的Spring Cloud应用程序。释放。使用zuul,spring security和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();

}

我希望在请求注销URL后,身份验证和会话无效

1 个答案:

答案 0 :(得分:1)

在您的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("/");
    }
}