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("*"));
|
// 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));
|
}
|
}
|