Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring CORS settings

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?

like image 919
Guigreg Avatar asked May 19 '26 02:05

Guigreg


2 Answers

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/

like image 150
Rahul Avatar answered May 21 '26 16:05

Rahul


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.

like image 40
Guigreg Avatar answered May 21 '26 16:05

Guigreg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!