Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring CORS No 'Access-Control-Allow-Origin' header is present

I am getting the following problem after porting web.xml to java config

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. 

Based on a few Spring references, the following attempt has been tried:

@Configuration @ComponentScan(basePackageClasses = AppConfig.class, useDefaultFilters = false, includeFilters = {         @Filter(org.springframework.stereotype.Controller.class) }) @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter {      @Override     public void addCorsMappings(CorsRegistry registry) {         registry.addMapping("/*").allowedOrigins("*").allowedMethods("GET", "POST", "OPTIONS", "PUT")                 .allowedHeaders("Content-Type", "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method",                         "Access-Control-Request-Headers")                 .exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")                 .allowCredentials(true).maxAge(3600);     }  } 

The values chosen were taken from a working web.xml filter:

<filter>     <filter-name>CorsFilter</filter-name> <filter-class>org.apache.catalina.filters.CorsFilter</filter-class> <init-param>     <param-name>cors.allowed.origins</param-name>     <param-value>*</param-value> </init-param> <init-param>     <param-name>cors.allowed.methods</param-name>     <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value> </init-param> <init-param>     <param-name>cors.allowed.headers</param-name>     <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value> </init-param> <init-param>     <param-name>cors.exposed.headers</param-name>     <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value> </init-param> <init-param>     <param-name>cors.support.credentials</param-name>     <param-value>true</param-value> </init-param> <init-param>     <param-name>cors.preflight.maxage</param-name>     <param-value>10</param-value> </init-param> </filter> <filter-mapping>  <filter-name>CorsFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 

Any ideas why the Spring java config approach is not working like the web.xml file did?

like image 314
Ian Mc Avatar asked Jan 29 '16 18:01

Ian Mc


People also ask

How do I fix CORS header Access-Control allow Origin missing?

If the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the Access-Control-Allow-Origin header's value. You can also configure a site to allow any site to access it by using the * wildcard. You should only use this for public APIs.

How do you set the Access-Control allow Origin header in spring boot?

You can add @CrossOrigin("http://localhost:8080") to proper method if you want :8080 to allow request there. It's a simple config for one endpoint/controller. You can use variable there too for customization later of course.

How do I enable CORS policy in spring boot?

Enable CORS in Controller Method We need to set the origins for RESTful web service by using @CrossOrigin annotation for the controller method. This @CrossOrigin annotation supports specific REST API, and not for the entire application.


2 Answers

Change the CorsMapping from registry.addMapping("/*") to registry.addMapping("/**") in addCorsMappings method.

Check out this Spring CORS Documentation .

From the documentation -

Enabling CORS for the whole application is as simple as:

@Configuration @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter {      @Override     public void addCorsMappings(CorsRegistry registry) {         registry.addMapping("/**");     } } 

You can easily change any properties, as well as only apply this CORS configuration to a specific path pattern:

@Configuration @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter {     @Override     public void addCorsMappings(CorsRegistry registry) {         registry.addMapping("/api/**")             .allowedOrigins("http://domain2.com")             .allowedMethods("PUT", "DELETE")             .allowedHeaders("header1", "header2", "header3")             .exposedHeaders("header1", "header2")             .allowCredentials(false).maxAge(3600);     } } 

Controller method CORS configuration

@RestController @RequestMapping("/account") public class AccountController {   @CrossOrigin   @RequestMapping("/{id}")   public Account retrieve(@PathVariable Long id) {     // ...   } } 

To enable CORS for the whole controller -

@CrossOrigin(origins = "http://domain2.com", maxAge = 3600) @RestController @RequestMapping("/account") public class AccountController {      @RequestMapping("/{id}")     public Account retrieve(@PathVariable Long id) {         // ...     }      @RequestMapping(method = RequestMethod.DELETE, path = "/{id}")     public void remove(@PathVariable Long id) {         // ...     } } 

You can even use both controller-level and method-level CORS configurations; Spring will then combine attributes from both annotations to create merged CORS configuration.

@CrossOrigin(maxAge = 3600) @RestController @RequestMapping("/account") public class AccountController {      @CrossOrigin("http://domain2.com")     @RequestMapping("/{id}")     public Account retrieve(@PathVariable Long id) {         // ...     }      @RequestMapping(method = RequestMethod.DELETE, path = "/{id}")     public void remove(@PathVariable Long id) {         // ...     } } 
like image 199
Omkar Puttagunta Avatar answered Sep 23 '22 19:09

Omkar Puttagunta


Helpful tip - if you're using Spring data rest you need a different approach.

@Component public class SpringDataRestCustomization extends RepositoryRestConfigurerAdapter {   @Override  public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {     config.getCorsRegistry().addMapping("/**")             .allowedOrigins("http://localhost:9000");   } } 
like image 24
reversebind Avatar answered Sep 21 '22 19:09

reversebind