在 Spring Security 过滤器链中手动设置 HTTP 状态码并写入响应体,会导致 ExceptionTranslationFilter 无法处理后续 AccessDeniedException,因其检测到响应已提交(committed)。本文提供一种解耦、符合框架设计原则的解决方案:将认证失败逻辑委托给 AuthenticationEntryPoint,通过请求属性传递异常上下文,实现统一、可维护的 JSON 错误响应。
在 spring security 过滤器链中手动设置 http 状态码并写入响应体,会导致 `exceptiontranslationfilter` 无法处理后续 `accessdeniedexception`,因其检测到响应已提交(committed)。本文提供一种解耦、符合框架设计原则的解决方案:将认证失败逻辑委托给 `authenticationentrypoint`,通过请求属性传递异常上下文,实现统一、可维护的 json 错误响应。
在基于 Cookie 或 Token 的无状态认证场景中(如 JWT、自定义 Cookie 认证),开发者常在自定义 OncePerRequestFilter(如 CookieAuthenticationFilter)中完成凭证解析与用户加载。当认证失败时,若直接调用 response.setStatus() 和 objectMapper.writeValue() 写入错误响应,会触发一个关键问题:HTTP 响应已被提交(response.isCommitted() == true)。此时,若后续流程(如权限校验)抛出 AccessDeniedException,Spring Security 的核心过滤器 ExceptionTranslationFilter 将拒绝处理该异常,并抛出 ServletException: Unable to handle the Spring Security Exception because the response is already committed —— 因为它必须在响应头未发送前介入,才能按配置的 AccessDeniedHandler 或 AuthenticationEntryPoint 统一格式化错误。
根本原因在于:ExceptionTranslationFilter 是 Spring Security 异常处理的“守门人”,它仅在响应未提交时才可安全接管 AuthenticationException 或 AccessDeniedException。而手动提前写响应,相当于绕过了整个框架的异常处理生命周期。
✅ 正确做法是 遵循委托模式(Delegate Pattern):不在认证过滤器中终结响应,而是将失败上下文“挂载”到请求中,交由框架标准入口点处理。
✅ 推荐实现方案
1. 修改 CookieAuthenticationFilter:仅传递异常,不写响应
@Component
public class CookieAuthenticationFilter extends OncePerRequestFilter {
private final AuthService authService;
private final ObjectMapper objectMapper;
public CookieAuthenticationFilter(AuthService authService, ObjectMapper objectMapper) {
this.authService = authService;
this.objectMapper = objectMapper;
}
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
// 提取 cookie(示例)
Cookie[] cookies = request.getCookies();
String authValue = null;
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("auth_token".equals(cookie.getName())) {
authValue = cookie.getValue();
break;
}
}
}
if (authValue == null) {
// 无凭证 → 触发 AuthenticationEntryPoint(无需手动设状态)
request.setAttribute(CookieAuthenticationEntryPoint.COOKIE_AUTH_ERROR_REQUEST_ATTR_KEY,
new CustomAuthException("Missing authentication token"));
filterChain.doFilter(request, response);
return;
}
try {
UserDto user = authService.getUserFromAuthenticationToken(
new AuthenticationTokenValueDto(authValue)
);
Authentication auth = new PreAuthenticatedAuthenticationToken(
user, authValue, Collections.emptyList()
);
SecurityContextHolder.getContext().setAuthentication(auth);
} catch (CustomAuthException e) {
// ✅ 关键修改:仅存异常到 request 属性,不操作 response
request.setAttribute(CookieAuthenticationEntryPoint.COOKIE_AUTH_ERROR_REQUEST_ATTR_KEY, e);
// 继续走过滤器链,让 ExceptionTranslationFilter 拦截并委派
}
filterChain.doFilter(request, response);
}
}2. 实现自定义 AuthenticationEntryPoint
@Component
public class CookieAuthenticationEntryPoint implements AuthenticationEntryPoint {
public static final String COOKIE_AUTH_ERROR_REQUEST_ATTR_KEY = "CookieAuthenticationError";
private final ObjectMapper objectMapper;
public CookieAuthenticationEntryPoint(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public void commence(
HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
// 优先检查是否携带自定义认证异常(来自 CookieAuthenticationFilter)
Object errorAttr = request.getAttribute(COOKIE_AUTH_ERROR_REQUEST_ATTR_KEY);
if (errorAttr instanceof Exception exception) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
Map<String, Object> errorResponse = Map.of(
"code", HttpServletResponse.SC_UNAUTHORIZED,
"message", exception.getMessage(),
"timestamp", Instant.now().toString()
);
objectMapper.writeValue(response.getOutputStream(), errorResponse);
return;
}
// 默认兜底:未登录访问受保护资源
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
objectMapper.writeValue(response.getOutputStream(), Map.of(
"code", HttpServletResponse.SC_UNAUTHORIZED,
"message", "Unauthorized access: missing or invalid credentials"
));
}
}3. 在 SecurityConfig 中注册入口点
@Configuration
@EnableWebSecurity
public class SecurityConfig {
private final CookieAuthenticationFilter cookieAuthenticationFilter;
private final CookieAuthenticationEntryPoint cookieAuthenticationEntryPoint;
public SecurityConfig(
CookieAuthenticationFilter cookieAuthenticationFilter,
CookieAuthenticationEntryPoint cookieAuthenticationEntryPoint) {
this.cookieAuthenticationFilter = cookieAuthenticationFilter;
this.cookieAuthenticationEntryPoint = cookieAuthenticationEntryPoint;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.cors(AbstractHttpConfigurer::disable)
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(a -> a
.requestMatchers("/un/**").permitAll()
.anyRequest().authenticated()
)
.exceptionHandling(e -> e
.authenticationEntryPoint(cookieAuthenticationEntryPoint) // ✅ 注册
// 可选:同时配置 AccessDeniedHandler 处理授权失败
.accessDeniedHandler(new JsonAccessDeniedHandler(objectMapper))
)
.addFilterBefore(cookieAuthenticationFilter, BasicAuthenticationFilter.class);
return http.build();
}
}? 补充:JsonAccessDeniedHandler 示例(用于 403 Forbidden)
public class JsonAccessDeniedHandler implements AccessDeniedHandler { private final ObjectMapper objectMapper; public JsonAccessDeniedHandler(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException { response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.setContentType(MediaType.APPLICATION_JSON_VALUE); objectMapper.writeValue(response.getOutputStream(), Map.of( "code", HttpServletResponse.SC_FORBIDDEN, "message", "Access denied: insufficient permissions" )); } }
⚠️ 注意事项与最佳实践
- 绝不提前提交响应:任何自定义过滤器中,禁止调用 response.setStatus() + write() + flush() 组合,除非你明确退出整个过滤器链且不再依赖 Spring Security 后续逻辑。
- 使用类型安全的属性键:生产环境建议用 private static final String 或更优的 AttributeKey<CustomAuthException>(需配合 HttpServletRequestWrapper),避免字符串硬编码风险。
- 异常分类要清晰:AuthenticationEntryPoint 专责 未认证/认证失败(401),AccessDeniedHandler 专责 已认证但无权访问(403)。二者职责分离,不可混淆。
- 线程安全考量:request.setAttribute() 是线程安全的(每个请求独享 HttpServletRequest 实例),无需额外同步。
- 兼容性保障:该方案完全兼容 Spring Security 6.x+(基于 SecurityFilterChain),无需关闭或替换 ExceptionTranslationFilter —— 它正是我们所依赖的基础设施。
通过此方式,你既保留了对认证失败响应格式的完全控制力,又无缝融入 Spring Security 的标准异常处理生命周期,确保所有安全异常(无论是认证失败还是授权拒绝)均能被统一、可靠、可测试地处理。

















