我正在使用 spring security web 5.0.9 和 tomcat 8。 ExceptionTranslationFilter throw ServletException “无法处理 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);
...
}
- 然后 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);
...
}
- 没有人捕获 ServletException 并且应用程序尝试查找 /web_framework/error_page/405.html
我发现此错误修复https://github.com/spring-projects/spring-security/issues/5273中更改了弹簧安全代码。
如何处理 ServletException 并返回有效的 401 响应,而不是 web_framework/error_page/405.html