Skip to content
Advertisement

Java – Spring Boot: Access-Control- Allow-Origin not working

I tried to implement Access-Control- Allow-Origin in spring boot using few tutorials and this link but not able to implement this.

To implement this, in application.properties file, I added below line

endpoints.cors.allowed-origins=https://example.com

Which probably means that except the URL https://example.com, no other endpoint can call any APIs. But it’s not working I still can see * in response , in below image. Which menas from other domains, my APIs are accessible. So how to prevent this?

enter image description here

Advertisement

Answer

Finally, I resolved this problem by adding the following in my Application class.

@Bean
public WebMvcConfigurer corsConfigurer() {

    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("https://example.com",
                            "https://www.example.com",
                            "http://192.168.1.12:3000",
                            "http://localhost:3000");
        }
    };
}

So the final Application class will look something similar to this

@SpringBootApplication
@EnableScheduling
@EnableAsync
public class ExampleApplication {

public static void main(String[] args) {
    SpringApplication.run(ExampleApplication.class, args);
}

@Bean
public WebMvcConfigurer corsConfigurer() {

    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("https://example.com",
                            "https://www.example.com",
                            "http://192.168.1.12:3000",
                            "http://localhost:3000");
        }
    };
   }
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement