Enabling Angular frontend access to controllers

The backend REST controllers will eventually run on their own web server and the Angular frontend will run on its own server. This means each runs with different origins (domain, protocol, port) and they need to communicate with each other. This is where cross-origin resource sharing (CORS) comes in. 

When client code like the Angular frontend tries to access an endpoint that is not residing in the same place as itself, the browser will send an HTTP OPTIONS request to the same endpoint to check whether the Angular frontend's origin is allowed. It will decide this by the response headers it receives from the OPTIONS request, such as ACCESS-CONTROL-ALLOW-ORIGIN, ACCESS-CONTROL-ALLOW-METHODS, and so on.

In order to support this, the following CorsFilter configuration needs to be done in the REST API backend:

@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new
UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new
CorsFilter(source));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}

The preceding filter allows all origins, all headers, and all methods for any endpoint.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.20.231