99import org .springframework .security .crypto .bcrypt .BCryptPasswordEncoder ;
1010import org .springframework .security .crypto .password .PasswordEncoder ;
1111import org .springframework .security .web .SecurityFilterChain ;
12+ import org .springframework .web .cors .CorsConfiguration ;
13+ import org .springframework .web .cors .CorsConfigurationSource ;
14+ import org .springframework .web .cors .UrlBasedCorsConfigurationSource ;
15+
16+ import java .util .List ;
1217
1318@ Configuration
1419@ EnableWebSecurity
@@ -18,15 +23,38 @@ public class SecurityConfig {
1823 public SecurityFilterChain securityFilterChain (HttpSecurity http ) throws Exception {
1924 http
2025 .csrf (AbstractHttpConfigurer ::disable ) // Desabilita CSRF (comum em APIs REST)
26+ .cors (cors -> cors .configurationSource (corsConfigurationSource ()))
2127 .sessionManagement (session -> session .sessionCreationPolicy (SessionCreationPolicy .STATELESS )) // API sem estado
2228 .authorizeHttpRequests (auth -> auth
2329 .anyRequest ().permitAll () // Por enquanto, libera tudo para você não se travar
2430 );
2531
2632 return http .build ();
2733 }
34+
35+ /**
36+ * Origens do front local e do compose: Vite (5173) e nginx da web (4173).
37+ * Evita {@code allowedOriginPatterns("*")} com {@code allowCredentials(true)}, combinação inválida na especificação CORS.
38+ */
39+ @ Bean
40+ public CorsConfigurationSource corsConfigurationSource () {
41+ CorsConfiguration configuration = new CorsConfiguration ();
42+ configuration .setAllowedOrigins (List .of (
43+ "http://localhost:5173" ,
44+ "http://127.0.0.1:5173" ,
45+ "http://localhost:4173" ,
46+ "http://127.0.0.1:4173"
47+ ));
48+ configuration .setAllowedMethods (List .of ("GET" , "POST" , "PUT" , "DELETE" , "PATCH" , "OPTIONS" ));
49+ configuration .setAllowedHeaders (List .of ("*" ));
50+ configuration .setAllowCredentials (false );
51+ UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource ();
52+ source .registerCorsConfiguration ("/**" , configuration );
53+ return source ;
54+ }
55+
2856 @ Bean
2957 public PasswordEncoder passwordEncoder () {
3058 return new BCryptPasswordEncoder ();
3159 }
32- }
60+ }
0 commit comments