Usando Spring 2.3.0.RELEASE, tuve la siguiente confirmación de CORS:
@Configuration @EnableWebSecurity @ComponentScan("com.softeq.ems.config") @EnableGlobalMethodSecurity(prePostEnabled = true) public class EmsJwtSecurityConfig extends BaseSecurityConfig { @Value("${management.endpoints.web.cors.allowed-origins}") private String[] allowedOrigins; @Override protected void configureHttp(HttpSecurity http) throws Exception { if (allowedOrigins.length > 0) { http.cors().configurationSource(corsConfigSource()); } http.csrf().disable(); } private CorsConfigurationSource corsConfigSource() { final CorsConfiguration corsConfig = new CorsConfiguration(); corsConfig.addAllowedHeader(CorsConfiguration.ALL); corsConfig.addAllowedMethod(CorsConfiguration.ALL); Stream.of(allowedOrigins).forEach( origin -> corsConfig.addAllowedOrigin(origin) ); return request -> corsConfig; } management.endpoints.web.cors.allowed-origins = http://localhost:4200, http://127.0.0.1:4200
Esta configuración funcionó bien y todas las solicitudes multiplataforma que necesitaba fueron autorizadas.
Pero después de migrar a spring-boot 2.4.0 después del lanzamiento, cuando intenté enviar una solicitud al host como de costumbre, recibí el clásico error de política cors en la consola del navegador Chrome:
Access to XMLHttpRequest at 'http://localhost:8080/api/v1/me/balance' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status Las notas de lanzamiento de Spring dicen que la configuración de cors proporciona una nueva propiedad allowedOriginPatterns , pero no entiendo cómo usarla: https://github.com/spring-projects/spring-framework/wiki/What%27s-New-in -Spring-Framework-5.x#revisión-web-general
¡Por favor, ayúdame a descubrir cuál es mi problema!
Aquí lo que le haría a tu código:
private CorsConfigurationSource corsConfigSource() { final CorsConfiguration corsConfig = new CorsConfiguration(); corsConfig.addAllowedHeader(CorsConfiguration.ALL); corsConfig.addAllowedMethod(CorsConfiguration.ALL); Stream.of(allowedOrigins).forEach( //origin -> corsConfig.addAllowedOrigin(origin) origin -> corsConfig.addAllowedOriginPattern(origin) ); return request -> corsConfig; }Lo hice así:
@Configuration @Profile("!production") class CorsConfig : WebMvcConfigurer { override fun addCorsMappings(registry: CorsRegistry) { registry .addMapping("/**") .allowedOriginPatterns("http://localhost:3000") } }