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。 * *
关键决策: *
生产环境用 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)); } }