Using Spring 2.3.0.RELEASE I had the following CORS confiruration:
@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;
}
Variable management.endpoints.web.cors.allowed-origins = http://localhost:4200, http://127.0.0.1:4200
This configuration worked fine and all the cross-platform requests I needed were authorized.
But after migrating to spring-boot 2.4.0 after the release, when I tried to send a request to the host as usual, I got the classic cors policy error in chrome browser console:
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
Spring release notes says that the cors configuration provides a new property allowedOriginPatterns
, but I don't understand how to use it:
https://github.com/spring-projects/spring-framework/wiki/What%27s-New-in-Spring-Framework-5.x#general-web-revision
Please help me figure out what my problem is!
Here what I would do to your code:
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;
}
I did it like this:
@Configuration
@Profile("!production")
class CorsConfig : WebMvcConfigurer {
override fun addCorsMappings(registry: CorsRegistry) {
registry
.addMapping("/**")
.allowedOriginPatterns("http://localhost:3000")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With