如何生成注销处理方法

时间:2019-01-14 17:22:41

标签: java spring spring-security logout


我正在尝试创建一种在Spring Security中处理注销操作的方法。
另外,我正在尝试在SecurityConfig中进行此操作without overriding the configure() method


LoginController

    @RequestMapping(value = "/logout")
    public String logoutDo(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession(false);
        SecurityContextHolder.clearContext();
        if (session != null) {
            session.invalidate();
        }
        for (Cookie cookie : request.getCookies()) {
            cookie.setMaxAge(0);
        }
    // update database here
        return "logout";
    }
}

homepage.jsp

     <c:url var="logoutUrl" value="/logout" />
     <a href="${logoutUrl}">Logout</a>

项目结构

project structure

点击注销链接后的输出

error view

我想找出为什么在单击logout link后不能执行logoutDo()方法的原因。
是否有任何默认注销过程可以覆盖此过程?
请帮忙。谢谢。

1 个答案:

答案 0 :(得分:2)

登出是handled by a filter,如果调用,将结束过滤器链并返回响应(通常是重定向)

这是由LogoutSuccessHandler

完成的

Spring Security的LogoutFilter的摘录

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    if (requiresLogout(request, response)) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        if (logger.isDebugEnabled()) {
            logger.debug("Logging out user '" + auth
                    + "' and transferring to logout destination");
        }

        this.handler.logout(request, response, auth);

        logoutSuccessHandler.onLogoutSuccess(request, response, auth);

        return;
    }

    chain.doFilter(request, response);
}

话虽如此,您始终可以禁用Spring Security的注销功能

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .logout()
                .disable()
        ;
    }

}