Last active
September 7, 2020 12:01
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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