我正在使用 spring security web 5.0.9 和 tomcat 8。ExceptionTranslationFilter 抛出 ServletException“无法处理 Spring Security 异常,因为响应已提交。” 我深入研究源代码并找到根本原因。我不确定这是否是 Spring Security 的一个错误。
我在 AuthenticationUserDetailsService.loadUserDetails 中抛出 UsernameNotFoundException
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);
...
}
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);
...
}
我发现 Spring Security 代码在此错误修复中发生了更改https://github.com/spring-projects/spring-security/issues/5273。
如何处理ServletException并返回有效的401响应,但不返回web_framework/error_page/405.html
这听起来可能是代码中的错误配置。
通常,如果调用
SimpleUrlAuthenticationFailureHandler
,则不会同时调用 ExceptionTranslationFilter
,因为不需要进一步的响应处理。