Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change of CORS policy in spring boot version 2.4.0

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!

like image 877
misnomer42 Avatar asked Nov 18 '20 13:11

misnomer42


2 Answers

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;
}
like image 168
YazidEF Avatar answered Sep 18 '22 10:09

YazidEF


I did it like this:

@Configuration
@Profile("!production")
class CorsConfig : WebMvcConfigurer {
    override fun addCorsMappings(registry: CorsRegistry) {
        registry
            .addMapping("/**")
            .allowedOriginPatterns("http://localhost:3000")
    }
}
like image 39
Dmitry Kaltovich Avatar answered Sep 20 '22 10:09

Dmitry Kaltovich