I built a simple Spring Boot rest api and have an Angular app making the http requests from another local port (all running locally). I had the following CORS filter in my @SpringBootApplication
class to permit the requests from my Angular app and all worked well.
public CorsFilter corsFilter() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
corsConfiguration.setAllowedHeaders(Arrays.asList("Origin", "Access-Control-Allow-Origin", "Content-Type",
"Accept", "Authorization", "Origin, Accept", "X-Requested-With",
"Access-Control-Request-Method", "Access-Control-Request-Headers"));
corsConfiguration.setExposedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "Authorization",
"Access-Control-Allow-Origin", "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials"));
corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
Then I added Spring Security as I want to secure my api. Now I keep getting Access to XMLHttpRequest has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have spent pretty much an entire day trying to figure this out in the Spring docs, but im clearly doing something wrong.
I replaced my CORS filter with the @Bean
as per this post, no no avail, I still get the same CORS error.
Spring security CORS Filter
e.g. in my @SpringBootApplication
annotated class I deleted my old cors filter and added:
@Bean
public WebMvcConfigurer configure() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:4200"); //Angular app port
}
};
}
I can make requests to my api via my brower from the port where the back is serving (8080) the issue is my Angular app running on port 4200 is making the requests to the back but getting blocked due to the CORs filter. Is there something else I have to configure?