首页 > 解决方案 > Spring Security ExceptionTranslationFilter 抛出“无法处理 Spring Security 异常,因为响应已经提交。”

问题描述

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

  1. 我在 AuthenticationUserDetailsS​​ervice.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 捕获它并检查响应提交状态,发现它是真的然后抛出异常
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

我发现此错误修复https://github.com/spring-projects/spring-security/issues/5273中更改了弹簧安全代码。

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

标签: servletsspring-securitytomcat8servletexception

解决方案


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

通常,如果SimpleUrlAuthenticationFailureHandler调用了 ,则ExceptionTranslationFilter不会调用 ,因为不需要进一步的响应处理。


推荐阅读