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
JavaScript
x
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?
Advertisement
Answer
Finally, I resolved this problem by adding the following in my Application class.
JavaScript
@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
JavaScript
@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");
}
};
}
}