fix: 修复sse重连抛出错误

This commit is contained in:
2026-08-14 00:59:42 +08:00
parent b382800301
commit 3322b0542b
@@ -1,23 +1,26 @@
package top.xyquan.ecomdmbbackend.common.config;
import jakarta.servlet.DispatcherType;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.core.AuthenticationException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import top.xyquan.ecomdmbbackend.common.filter.JwtAuthenticationFilter;
import top.xyquan.ecomdmbbackend.modules.open.api.filter.ApiKeyAuthenticationFilter;
import java.io.IOException;
/**
* Spring Security配置
*/
@@ -45,6 +48,13 @@ public class SecurityConfig {
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
// SSE:建连走 REQUEST(仍需 JWT);断开后 Tomcat 的 ASYNC/ERROR/FORWARD 调度无 SecurityContext,
// 再鉴权会 AccessDenied,且 response 已提交只会刷噪音堆栈
.dispatcherTypeMatchers(
DispatcherType.ASYNC,
DispatcherType.ERROR,
DispatcherType.FORWARD)
.permitAll()
.requestMatchers("/api/auth/login", "/api/auth/register", "/api/auth/refresh").permitAll()
.requestMatchers("/api/channel/pdd/auth/callback").permitAll()
.requestMatchers("/uploads/**").permitAll() // 允许直接访问上传的文件
@@ -53,7 +63,8 @@ public class SecurityConfig {
.permitAll()
.anyRequest().authenticated())
.exceptionHandling(exceptions -> exceptions
.authenticationEntryPoint(new CustomAuthenticationEntryPoint()))
.authenticationEntryPoint(new CustomAuthenticationEntryPoint())
.accessDeniedHandler(committedSafeAccessDeniedHandler()))
// 两个自定义 Filter 均锚定到 UsernamePasswordAuthenticationFilter;
// 后注册的执行更靠前,故先注册 JWT、再注册 ApiKey,保证 /open/** 先走 ApiKey
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
@@ -62,6 +73,20 @@ public class SecurityConfig {
return http.build();
}
/**
* SSE 等长连接断开时 response 可能已 committed,此时写 403 会二次失败。
*/
private static AccessDeniedHandler committedSafeAccessDeniedHandler() {
return (request, response, accessDeniedException) -> {
if (response.isCommitted()) {
return;
}
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("{\"code\":403,\"message\":\"无权限访问\",\"data\":null}");
};
}
/**
* 自定义认证入口点,返回401状态码
*/
@@ -69,6 +94,9 @@ public class SecurityConfig {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
if (response.isCommitted()) {
return;
}
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("{\"code\":401,\"message\":\"登录已过期,请重新登录\",\"data\":null}");