“ Spring Security ExceptionTranslationFilter throw”由于响应已提交,因此无法处理Spring Security Exception。

时间:2019-04-12 10:21:26

标签: servlets spring-security tomcat8 servletexception

我正在使用Spring Security Web 5.0.9和tomcat8。ExceptionTranslationFilter抛出ServletException“由于响应已经提交,因此无法处理Spring Security Exception。 我深入研究源代码并找到根本原因。我不确定这是否是Spring安全性的错误。

  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中的spring安全代码已更改。

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

1 个答案:

答案 0 :(得分:0)

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

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