Issue
im working in spring projet where i want to allow multiple origins call my backen API. so far my config works only for one origin. and this is my code :
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOriginPattern("myoriginone");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
do you have any idea how i can allow multiple origins. something like "host1","host2".. since the addAllowedOriginPattern() method accept only one string param.
Regards.
Solution
If you see the docs, the allowedOrigins
is an array.
@Nullable
private List<String> allowedOrigins;
and the following method is setting the allowed Origins. Clearly, you can invoke the method multiple times to add the different origins.
/**
* Add an origin to allow.
*/
public void addAllowedOrigin(String origin) {
if (this.allowedOrigins == null) {
this.allowedOrigins = new ArrayList<>(4);
}
else if (this.allowedOrigins == DEFAULT_PERMIT_ALL) {
setAllowedOrigins(DEFAULT_PERMIT_ALL);
}
this.allowedOrigins.add(origin);
}
OR
Use the following
public void setAllowedOrigins(@Nullable List<String> allowedOrigins) {
this.allowedOrigins = (allowedOrigins != null ? new ArrayList<>(allowedOrigins) : null);
}
Answered By - harry
Answer Checked By - Katrina (JavaFixing Volunteer)