1. Cross-Origin Resource Sharing (CORS) is a security concept.
2. It prevents the JavaScript code to produce or consume the requests against the Rest API.
For example, your web application (says Angular Application) is running on 4200 port and by using JavaScript you are trying to consuming RESTful web services from 9090 port. Under such situations, you will face the Cross-Origin Resource Sharing security issue on your web browsers.
3. Two requirements are needed to handle this issue −
2. It prevents the JavaScript code to produce or consume the requests against the Rest API.
For example, your web application (says Angular Application) is running on 4200 port and by using JavaScript you are trying to consuming RESTful web services from 9090 port. Under such situations, you will face the Cross-Origin Resource Sharing security issue on your web browsers.
3. Two requirements are needed to handle this issue −
- RESTful web services should support the Cross-Origin Resource Sharing.
- RESTful web service application should allow accessing the API(s) from the 8080 port.
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.
@RequestMapping(value = "/products") @CrossOrigin(origins = "http://localhost:8080") public ResponseEntity<Object> getProduct() { return null; }
Global CORS Configuration
We need to define the shown @Bean configuration to set the CORS configuration support globally to your Spring Boot application.
@Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/products").allowedOrigins("http://localhost:9000"); } }; }
0 comments :
Post a Comment