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
I was trying to configure CORS globally via WebMvcConfigurerAdapter shown yours with log. And I found log message but it got error like
Access to XMLHttpRequest at 'myurl' from origin 'some origin' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Controll-Allow-Origin' header is presnet on the requested resource.
My Case was also good at @CrossOrigin but not in globally configure. I hope this will be helped.
The reason is web.xml.
1. I have <context:component-scan base-package="some base-package"> but class WebConfig is not in 'some base-package' package, It's in the upper package. I moved WebConfig to 'some base-package' package and
2. I removed <mvc:annotation-driven /> because I have already have @EnableWebMvc in WebConfig class.
It works.
you didn't declared method in it which is by default accept only get method.
try registry.allowedMethods("*");
I was able to get the Spring Global CORS configuration to work, after experiencing the exact problem documented in this issue. I had to do 2 things:
allowedOrigins cannot be * if allowCredentials is true. This is documented at Mozilla.org
Remove mvc:annotation-driven from the spring XML. Cannot have BOTH the XML config and @EnableWebMvc. The global class won't work without @EnableWebMvc, thus mvc:annotation-driven must be removed.
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!