package com.custom.webui.config; import com.custom.webui.dto.resp.Result; import com.custom.webui.security.JwtAuthenticationFilter; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; 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.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import java.util.List; /** * Spring Security 配置:JWT 无状态认证 + CORS。 * *

关键决策: *

*/ @Configuration @EnableWebSecurity @EnableMethodSecurity @RequiredArgsConstructor public class SecurityConfig { private final JwtAuthenticationFilter jwtAuthenticationFilter; private final ObjectMapper objectMapper; @Bean public PasswordEncoder passwordEncoder() { // BCrypt 自带盐值,同一明文每次加密结果不同,无需额外加盐 return new BCryptPasswordEncoder(); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf(csrf -> csrf.disable()) .cors(cors -> cors.configurationSource(corsConfigurationSource())) .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .authorizeHttpRequests(auth -> auth // 预检请求直接放行,否则浏览器 CORS 会失败 .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 登录 / 注册 .requestMatchers("/api/auth/login", "/api/auth/register").permitAll() // SSE 长连接:EventSource 无法带 Header,靠 query token 认证 .requestMatchers(HttpMethod.GET, "/api/chats/*/stream").permitAll() // 健康检查与静态资源 .requestMatchers("/actuator/health", "/error").permitAll() // smoke profile 下的 H2 控制台 .requestMatchers("/h2-console/**").permitAll() // 其余全部需要认证 .anyRequest().authenticated()) // 未认证 / 无权限时返回统一 JSON 结构,而不是 Spring 默认的 HTML 页面 .exceptionHandling(ex -> ex .authenticationEntryPoint((request, response, authException) -> writeJson(response, HttpServletResponse.SC_UNAUTHORIZED, Result.error(401, "未登录或登录已过期"))) .accessDeniedHandler((request, response, deniedException) -> writeJson(response, HttpServletResponse.SC_FORBIDDEN, Result.error(403, "无权访问该资源")))) // H2 控制台使用 iframe,仅开发期需要 .headers(headers -> headers.frameOptions(frame -> frame.sameOrigin())) .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); } /** * CORS 配置:允许前端 dev server 跨域访问。 * *

生产环境用 nginx 同源反代时不需要 CORS,可把 allowedOriginPatterns 收紧。 * 注意开启了 allowCredentials,不能用 {@code "*"},必须用 pattern。 */ @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOriginPatterns(List.of( "http://localhost:*", "http://127.0.0.1:*", // 局域网访问:按你的实际网段调整 "http://192.168.*.*:*", "http://10.*.*.*:*")); config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS")); config.setAllowedHeaders(List.of("*")); // SSE 不需要暴露额外头,保留 Content-Type 便于前端判断 config.setExposedHeaders(List.of("Content-Type")); config.setAllowCredentials(true); config.setMaxAge(3600L); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return source; } /** 把 Result 对象写成 JSON 响应体 */ private void writeJson(HttpServletResponse response, int status, Result body) throws java.io.IOException { response.setStatus(status); response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.setCharacterEncoding("UTF-8"); response.getWriter().write(objectMapper.writeValueAsString(body)); } }