繁体   English   中英

Spring Security 注销不起作用 - 不清除安全上下文并且经过身份验证的用户仍然存在

[英]Spring Security logout does not work - does not clear security context and authenticated user still exists

我知道,有很多关于这个主题的文章,但我有一个问题,我找不到任何解决方案。

我有一个经典的 spring 安全 java 配置:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private AuctionAuthenticationProvider auctionAuthenticationProvider;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(auctionAuthenticationProvider);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic();

    ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry authorizeRequest = http.authorizeRequests();

    configureAdminPanelAccess(authorizeRequest);
    configureFrontApplicationAccess(authorizeRequest);
    configureCommonAccess(authorizeRequest);

    http.csrf()
        .csrfTokenRepository(csrfTokenRepository()).and()
        .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);

    http.logout()
        .clearAuthentication(true)
        .invalidateHttpSession(true);
}
...
}

此外,我有两个控制器方法,我通过 AJAX 从我的 Web 应用程序登录/注销。

当我想注销时,我首先调用此方法,我希望清除用户会话并清除安全上下文中的所有内容。

@Override
@RequestMapping(value = "/logout", method = GET, produces = APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Boolean> logout(final HttpServletRequest request, final HttpServletResponse response) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null){
        new SecurityContextLogoutHandler().logout(request, response, auth);
    }

    return new ResponseEntity<>(Boolean.TRUE, HttpStatus.OK);
}

在此之后,我重新加载客户端 Web 应用程序,每次重新加载时,我都会通过调用以下控制器方法来检查用户是否已通过身份验证:

@Override
@RequestMapping(value = "/user", method = GET, produces = APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<UserDetails> user() {
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if (principal instanceof UserDetails) {
        return new ResponseEntity<>((UserDetails) principal, HttpStatus.OK);
    }

    return null;
}

在这里,我将收到最后一个经过身份验证的用户。 好像在之前的注销方法中,Spring注销是不行的。

请记住,我尝试使用以下代码注销,但没有成功:

   @Override
   @RequestMapping(value = "/logout", method = GET, produces = APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<Boolean> logout(final HttpServletRequest request) {
     try {
         request.logout();

         return new ResponseEntity<>(Boolean.TRUE, HttpStatus.OK);
     } catch (ServletException ex) {
         if (LOG.isDebugEnabled()) {
             LOG.debug("There is a problem with the logout of the user", ex);
         }
    }

您知道我在配置和注销过程中遗漏了什么吗?

从您的问题中,我看到您正在尝试创建自己的注销,并且您还尝试使用默认的 Spring 注销。 我建议您应该选择一种方法,而不是将它们混合使用。 我建议从 Spring 注销有两个:

第一:默认 spring 安全注销

.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/logout.done").deleteCookies("JSESSIONID")
.invalidateHttpSession(true) 

从上面的示例中,您应该只需要在想要注销用户时调用/logout URL。 无需创建任何@Controller来处理该注销,而 Spring 将帮助用户注销。 您还可以在此处添加其他要失效的内容。

第二:以编程方式注销

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

    return "logout";
}

如果您使用这种注销方法,则不需要在 ht eSpring 安全配置中包含第一种方法。 通过使用此方法,您可以在注销完成前后添加要执行的额外操作。 顺便说一句,要使用此注销,只需调用/logout url,用户将被手动注销。 此方法将使会话无效,清除 Spring 安全上下文和 cookie。

另外对于第二种方法,如果您使用RequestMethod.POST ,则需要在 POST 请求中包含 CSRF 密钥。 另一种方法是创建一个带有隐藏输入 CSRF 密钥的表单。 这是使用 jQuery 自动生成注销链接的一些示例:

$("#Logout").click(function(){
    $form=$("<form>").attr({"action":"${pageContext.request.contextPath}"+"/logout","method":"post"})
    .append($("<input>").attr({"type":"hidden","name":"${_csrf.parameterName}","value":"${_csrf.token}"}))
    $("#Logout").append($form);
    $form.submit();
});

您只需要创建一个超链接<a id="Logout">Logout</a>即可使用它。

如果您使用RequestMethod.GET ,只需在您的链接中包含一个 CSRF 密钥作为参数,如下所示:

<a href="${pageContext.request.contextPath}/logout?${_csrf.parameterName}=${_csrf.token}">Logout</a>

就这些,希望有帮助。

这会有所帮助,我认为 clearAuthentication(true) 就足够了:

@Configuration 
@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter {

....

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http
        .httpBasic()
        .and()
        .logout().clearAuthentication(true)
        .logoutSuccessUrl("/")
        .deleteCookies("JSESSIONID")
        .invalidateHttpSession(true)
        .and()

请注意,有如下所示的清除站点数据HTTP 标头

Clear-Site-Data: "cache", "cookies", "storage", "executionContexts"

我还帮助在Spring-Security 5.2项目中添加了对Clear-Site-Data标头的支持。 有关实现的更多详细信息,请参阅PR

这是它如何工作的示例

@EnableWebSecurity
static class HttpLogoutConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .logout()
                    .addLogoutHandler(new HeaderWriterLogoutHandler(
                           new ClearSiteDataHeaderWriter(SOURCE)));
    }
}

其中 SOURCE 是以下一项或多项的vararg

  • "*"清除一切
  • "cache", "cookies", "storage", "executionContexts"一项或多项

有关更多详细信息,请参阅LogoutConfigurerClearSiteDataTests.java 中的示例测试。

我通过将以下参数添加到 application.properties 文件类似地解决了我的问题

spring.cache.type=NONE

在此处输入图片说明

只需将注销 URL 从“/注销”更改为“战争或快照名称/注销”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM