Hi @Gholap Amol ,
Thanks for reaching out.
I understand you are trying to call protected web-api through angular web application and getting CORS error.
This is due to when the two applications are hosted at different domains then browser security prevents a web page from making requests to another domain. This restriction prevents a malicious site from reading sensitive data from another site.
Cross Origin Resource Sharing (CORS) allows a server to relax this restriction and allow cross domain calls.
To enable CORS in spring Boot to allow request from web application using controller method or globally:
- Add @CrossOrigin annotation to specific action method to allow requests from http://localhost:4200 or add @CrossOrigin as class level as well. @CrossOrigin(origins = "http://localhost:4200")
@GetMapping("/products")
public Product getProduct(@RequestParam(required = false, defaultValue = "Books") String name)
{
.....
.....
} - You can enable CORS globally to accepts requests to access Web API for each methods by adding CORS mapping in Spring MVC configuration. public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/products").allowedOrigins("http://localhost:4200");
}
};
} 3.If you are using Spring Security, you can easily add cors in security configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()...
}
}
For granular access, you can apply CORS configuration to specific path using three parameters to allow calls with specific conditions:
1.Origin - Use the URI where you deployed the WebApp. This allows cross-origin requests from your WebApp only, while still disallowing all other cross-domain requests.
2.Headers - application/x-www-form-urlencoded, multipart/form-data, text/plain
3.Methods - GET, PUT, and POST methods calls are allowed. You can restrict GET calls only.
Reference : https://spring.io/guides/gs/rest-service-cors/
Hope this will help.
Thanks,
Shweta
Please remember to "Accept Answer" if answer helped you.