Spring Security ExceptionTranslationFilter 抛出“无法处理 Spring Security 异常,因为响应已提交。”

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

我正在使用 spring security web 5.0.9 和 tomcat 8。ExceptionTranslationFilter 抛出 ServletException“无法处理 Spring Security 异常,因为响应已提交。” 我深入研究源代码并找到根本原因。我不确定这是否是 Spring Security 的一个错误。

  1. 我在 AuthenticationUserDetailsService.loadUserDetails 中抛出 UsernameNotFoundException

  2. SimpleUrlAuthenticationFailureHandler.onAuthenticationFailure 捕获异常然后调用

public void onAuthenticationFailure(HttpServletRequest request,
            HttpServletResponse response, AuthenticationException exception)
            throws IOException, ServletException {

        if (defaultFailureUrl == null) {
            logger.debug("No failure URL set, sending 401 Unauthorized error");

            response.sendError(HttpStatus.UNAUTHORIZED.value(),
                HttpStatus.UNAUTHORIZED.getReasonPhrase());
        }

sendError 会将响应提交设置为 true,请参阅 ResponseFacade.java:

    public void sendError(int sc, String msg)
        throws IOException {
        ...
        response.setAppCommitted(true);
        ...

    }
  1. 然后ExceptionTranslationFilter捕获它并检查响应提交状态,发现它是true然后抛出异常
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
    ...
    if (response.isCommitted()) {
      throw new ServletException("Unable to handle the Spring Security Exception because the response is already committed.", ex);
    ...
}
  1. 没有人捕获 ServletException,应用程序尝试查找 /web_framework/error_page/405.html

我发现 Spring Security 代码在此错误修复中发生了更改https://github.com/spring-projects/spring-security/issues/5273

如何处理ServletException并返回有效的401响应,但不返回web_framework/error_page/405.html

servlets spring-security tomcat8 servletexception
1个回答
0
投票

这听起来可能是代码中的错误配置。

通常,如果调用

SimpleUrlAuthenticationFailureHandler
,则不会同时调用
ExceptionTranslationFilter
,因为不需要进一步的响应处理。

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