SecurityContextLogoutHandler清除身份验证即使设置为'false'

问题描述 投票:1回答:1

我目前正在尝试使用Spring Security在Spring Boot 2中为我们的应用程序实现注销机制。

我弹出安全的注销配置是:

http
    .logout()
    .logoutRequestMatcher(new AntPathRequestMatcher("/logout.html"))
    .logoutSuccessHandler(logoutSuccessHandler)
    .addLogoutHandler(handler1)
    .addLogoutHandler(handler2)
    .clearAuthentication(false);

通过这种配置,Spring将两个处理程序添加到LogoutFilter以及Spring自己的SecurityContextLogoutHandler作为处理程序链中的最后一个处理程序。

我们面临的问题是,在我们的自定义LogoutSuccessHandler中,我需要访问存储在安全上下文中的Authentication中的一些变量,但即使SecurityContextLogoutHandler设置为.clearAuthentication(boolean clearAuthentication),也会在false中清除上下文。

我真正不理解的是在logout中实施SecurityContextLogoutHandler方法。

public void logout(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) {
    Assert.notNull(request, "HttpServletRequest required");
    if (invalidateHttpSession) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            logger.debug("Invalidating session: " + session.getId());
            session.invalidate();
        }
    }

    if (clearAuthentication) {
        SecurityContext context = SecurityContextHolder.getContext();
        context.setAuthentication(null);
    }

    SecurityContextHolder.clearContext();
}

即使我将clearAuthentication设置为false,也没关系,因为SecurityContextHolder.clearContext();方法的最后一行无论如何都会清除它。

clearAuthentication标志有什么意义?如果需要,如何保留身份验证?

java spring spring-security
1个回答
0
投票

我已经看过源代码和文档,这是基于Spring Security版本4.2.X.

SecurityContextHolder.clearContext();不清楚背景的内容,但将其从SecurityContextHolder的控股策略中删除。除此之外,还有以下策略:

  • ThreadLocal的
  • 可继承的ThreadLocal
  • 全球

我相信有人会指出在哪里阅读这些不同的策略,但这与这个答案并不相关。

clearAuthentication标志的重点是什么

JavaDocs说:“如果为true,则从SecurityContext中删除身份验证以防止并发请求出现问题。”

也就是说,它与你在这种特殊情况下试图做的事情几乎没有关系。

如果需要,如何保留身份验证?

你实现LogoutSuccessHandler,其中Authentication对象直接传递到onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)。您无需执行任何其他任何操作即可访问该对象。

© www.soinside.com 2019 - 2024. All rights reserved.