javaspringspring-mvcswagger-codegen

Can you completely disable CORS support in Spring?


As described in CORS preflight request fails due to a standard header if you send requests to OPTIONS endpoints with the Origin and Access-Control-Request-Method headers set then they get intercepted by the Spring framework, and your method does not get executed. The accepted solution is the use @CrossOrigin annotations to stop Spring returning a 403. However, I am generating my API code with Swagger Codegen and so I just want to disable this and implement my OPTIONS responses manually.

So can you disable the CORS interception in Spring?


Solution

  • For newer versions of spring boot:

    @Configuration
    public class WebConfiguration implements WebMvcConfigurer {
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedMethods("*");
        }
    }
    
    

    The Kotlin way

    @Configuration
    class WebConfiguration : WebMvcConfigurer {
        override fun addCorsMappings(registry: CorsRegistry) {
            registry.addMapping("/**").allowedMethods("*")
        }
    }