Spring Global CORS configuration not working but Controller level config does

后端 未结 10 1076
臣服心动
臣服心动 2020-12-14 06:25

I am trying to configure CORS globally via WebMvcConfigurerAdapter shown below. To test I am hitting my API endpoint via a small node app I created to emulate a

10条回答
  •  失恋的感觉
    2020-12-14 07:12

    I had a similar issue and none of methods seemed to work (except using @CrossOrigin annotation for each controller). I followed Bharat Singh's solution above and after some debugging of Spring Framework internals - here's what worked for me (Spring Boot 2.0.6 + Spring Framework 5.0.10):

    @Configuration
    public class WebMvcConfiguration extends WebMvcConfigurationSupport {
    
    /* (non-Javadoc)
     * @see org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport#addCorsMappings(org.springframework.web.servlet.config.annotation.CorsRegistry)
     */
    @Override
    protected void addCorsMappings(CorsRegistry registry) {
        //NOTE: servlet context set in "application.properties" is "/api" and request like "/api/session/login" resolves here to "/session/login"!
        registry.addMapping("/**")
            .allowedMethods("GET", "POST", "PUT", "DELETE")
            .allowedOrigins("*")
            .allowedHeaders("*")
            .allowCredentials(false);
        }
    }
    

    Initially when I used "/api/**" mapping it was configured within Spring, but since the application was deployed with "/api" context - requests like "/api/session/login" were internally mapped to "/session/login" and such mapping in CORS configuration was not found - please pay attention to that!

提交回复
热议问题