spring-bootcorsspring-restcontrollercross-origin-resource-policy

In Spring Boot 2.5, how do I apply the @CrossOrigin annotation to a specific profile only?


I'm using SPring Boot 2.5. I have this at the top of my controller

@RestController
@CrossOrigin(origins = "*", allowedHeaders = "*")
public MyController {

This is to allow my local JS application to connect from a different port than what Spring Boot is running on. However, I don't want this cross origin policy to be in any other environment besides local. How can I modify the above so that I can apply the @CrossOrigin annotation only to a specific profile?


Solution

  • You can do that if you remove the @CrossOrigin annotation from the controller and apply the CORS config programmatically using a custom WebMvcConfigurer bean which is initialized only for a specific profile. The bean definition would look something like below:

        @Bean
        @Profile("local")
        public WebMvcConfigurer corsConfigurer() {
            return new WebMvcConfigurer() {
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/**")
                            .allowedOrigins("*")
                            .allowedMethods("*")
                            .allowedHeaders("*");
                }
            };
        }
    

    The corsConfigurer bean will be initialized only when the application is started with the local profile, which can be done by setting the value of the spring.profiles.active system property or SPRING_PROFILES_ACTIVE environment variable to local. Something like one of the below commands can be used to start the application with local profile:

    SPRING_PROFILES_ACTIVE=local java -jar myapp.jar
    java -Dspring.profiles.active=local -jar myapp.jar
    

    A sample app that uses this cors config can be found on github