kongdeqiang
2026-10-12 ccf1a44c001e233c158bd168dc2d0d96721af929
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
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。
 *
 * <p>关键决策:
 * <ul>
 *   <li><b>关闭 CSRF</b>:前后端分离 + JWT 放 Header,不依赖 Cookie,
 *       不存在 CSRF 攻击面</li>
 *   <li><b>STATELESS</b>:不创建 HttpSession,每次请求靠 JWT 重建认证上下文。
 *       这对 SSE 很重要 —— 若用 Session,长连接会长期占用会话资源</li>
 *   <li><b>SSE 路径放行</b>:{@code /api/chats/{chatId}/stream} 由 JwtAuthenticationFilter
 *       从 query 参数取 token 完成认证,因此在 authorizeHttpRequests 里设为 permitAll,
 *       但未带合法 token 的请求仍会被后续的 userId 空值校验挡在业务层外</li>
 * </ul>
 */
@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 跨域访问。
     *
     * <p>生产环境用 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("*"));
        // 浏览器只允许前端脚本读取**显式暴露**的响应头。
        // 导出接口的建议文件名就放在 Content-Disposition 里:
        // 不暴露的话,即使响应里有这个头前端也读不到,
        // 只能退回本地拼的文件名 —— 中文标题与时间戳就丢了。
        config.setExposedHeaders(List.of("Content-Type", "Content-Disposition"));
        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));
    }
}