I'm trying to enable the cross origin header to be able to reach the service from anywhere (only on local env) but I cannot.
@Configuration
@RequiredArgsConstructor
public class CrossOriginConfig implements WebMvcConfigurer {
private final SecurityConfiguration securityConfiguration;
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("*").allowedOrigins(securityConfiguration.getCrossOrginFilter());
}
}
I made a custom index.html with an ajax call and it fails due to the Allow-Cross-Origin header missing and it comes from another origin.
Simple Spring Boot 2.0 controllers are used with @RestController annotation and simple @GetMapping.
What I missed? What should I include and where?
You need to add the below annotation on either on the controller class or the specific method:
@CrossOrigin
By default, its allows all origins, all headers, the HTTP methods specified in the @RequestMapping annotation and a maxAge of 30 minutes is used.
If you want to allow only http://localhost:8080 to send cross-origin requests
@CrossOrigin(origins = "http://localhost:8080")
Replace the host and port accordingly.
Check the below Spring documentation for more information:
https://spring.io/guides/gs/rest-service-cors/
As Georg Wittberger pointed out the problem was with the mapping. I used the * wildcard what is not good for paths.
Instead of this: registry.addMapping("*")
I used this: registry.addMapping("/**") and it's working fine.
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