Skip to content

Instantly share code, notes, and snippets.

@Akhi1
Last active September 7, 2020 12:01
Show Gist options
  • Save Akhi1/52ca3148c06d15f1d8bc114b90f5a6e1 to your computer and use it in GitHub Desktop.
Save Akhi1/52ca3148c06d15f1d8bc114b90f5a6e1 to your computer and use it in GitHub Desktop.
Bean for Springboot application that will configure CORS -Sometimes you might need to GET the json code generated in swagger to parse
// Append this code to the main class
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// Allow anyone and anything access. Probably ok for Swagger spec
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/v3/api-docs", config);
return new CorsFilter(source);
}
// If the above doesn't work
// ******************************************
@Bean
public FilterRegistrationBean<CorsFilter> simpleCorsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.setAllowedOrigins(Arrays.asList("*"));
config.setAllowedMethods(Collections.singletonList("*"));
config.setAllowedHeaders(Collections.singletonList("*"));
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment