我在使用 spring webFlux 制作的项目中启用了 spring security + CORS。我的问题是我们接受来自以下机构的请求:http://本地主机:4200 http://localhost:4200。我怎样才能让 CORS 接受来自的请求http://*.localhost:4200 like http://a.localhost:4200 http://a.localhost:4200, http://b.localhost:4200 http://b.localhost:4200 ?
我的 CORS 配置如下所示:
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public CorsWebFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.setAllowedOrigins(corsConfigData.getAllowedOrigins());
config.setAllowedHeaders(corsConfigData.getAllowedHeaders());
config.setAllowedMethods(corsConfigData.getAllowedMethods());
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
你有什么想法 ???
我想我找到了一个有效的解决方案。这仅仅意味着创建一个自定义 CorsConfiguration,覆盖 checkOrigin 方法并创建一个将解释的自定义匹配器http://*.localhost:4200正确。代码如下所示:
public class RegexCorsConfiguration extends CorsConfiguration {
private List<String> allowedOriginsRegexes = new ArrayList<>();
/**
* Check the origin of the request against the configured allowed origins.
* @param requestOrigin the origin to check
* @return the origin to use for the response, possibly {@code null} which
* means the request origin is not allowed
*/
public String checkOrigin(String requestOrigin) {
if (!StringUtils.hasText(requestOrigin)) {
return null;
}
if (this.allowedOriginsRegexes.isEmpty()) {
return null;
}
if (this.allowedOriginsRegexes.contains(ALL)) {
if (getAllowCredentials() != Boolean.TRUE) {
return ALL;
} else {
return requestOrigin;
}
}
for (String allowedOriginRegex : this.allowedOriginsRegexes) {
if (createMatcher(requestOrigin, allowedOriginRegex).matches()) {
return requestOrigin;
}
}
return null;
}
public void setAllowedOriginRegex(List<String> allowedOriginsRegexes) {
this.allowedOriginsRegexes = allowedOriginsRegexes;
}
private Matcher createMatcher(String origin, String allowedOrigin) {
String regex = this.parseAllowedWildcardOriginToRegex(allowedOrigin);
Pattern pattern = Pattern.compile(regex);
return pattern.matcher(origin);
}
private String parseAllowedWildcardOriginToRegex(String allowedOrigin) {
String regex = allowedOrigin.replace(".", "\\.");
return regex.replace("*", ".*");
}}
当然,从配置类注入 corsConfig,如下所示:
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public CorsWebFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
RegexCorsConfiguration regexCorsConfiguration = new RegexCorsConfiguration();
regexCorsConfiguration.setAllowCredentials(true);
regexCorsConfiguration.setAllowedOriginRegex(corsConfigData.getAllowedOrigins());
regexCorsConfiguration.setAllowedHeaders(corsConfigData.getAllowedHeaders());
regexCorsConfiguration.setAllowedMethods(corsConfigData.getAllowedMethods());
source.registerCorsConfiguration("/**", regexCorsConfiguration);
return new CorsWebFilter(source);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)