我正在尝试定义允许执行REST服务的origins
。我正在研究Java(1.8),SpringBoot(1.5.9)。我尝试以两种方式实施 CORS:
@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping(value="/questions")
public String readCSV() throws IOException, URISyntaxException {
/** Some Logic **/
return str;
}
或
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
String origins = "http://localhost:8080";
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("GET", "PUT", "POST")
.allowedOrigins(origins)
.maxAge(3600);
super.addCorsMappings(registry);
}
}
上述两种情况都有效。但是我想将该http://localhost:8080
更改为一些有意义的正则表达式,它将与某些特定域名匹配,但 subdoamin 名称和端口号可能会有所不同。
例如,假设所需的域名是innovation.com并且很少接受的 url会被we.innovation.com:8081、my.innovation.com:8090等.
问题是,每当我放置一些正则表达式而不是静态 URL 时,它都会抛出 CORS 错误并且不允许访问该服务。即使在我使用允许任何有效 url 的正则表达式的情况下,它也会阻止localhost:8080
.
我尝试过这样的正则表达式:^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\.)+innovation.com(:d{2,4})
^https?://(?:[^./@]+.)*domain.com(?![^/])
^(http[s]://)?([A-Za-z0-9-]{1,63}\.)+innovation.com(:d{2,4})
一种解决方案是扩展 spring cors 配置,有一个名为 checkOrigin 的方法,可以重写它来处理正则表达式: https://github.com/spring-projects/spring-framework/blob/master/spring-web/src/main/java/org/springframework/web/cors/CorsConfiguration.java#L425-L455
幸运的是,有人已经这样做了:https://github.com/looorent/spring-security-jwt/blob/master/src/main/java/be/looorent/security/jwt/RegexCorsConfiguration.java
从SpringBoot 2.4.x或Spring 5.3开始,CorsRegistration可以将origin添加为模式。请参阅 CorsRegistration#allowOriginPatterns
这可以使用config.setAllowedPatterns(List.of("http://*.localhost:4200"));
查看差异,它setAllowedPatterns
不setAllowedOrigins
示例代码:
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("https://yourowndomain.com"));
configuration.setAllowedOriginPatterns(Arrays.asList("https://*.otherdomain.com"));
configuration.setAllowedMethods(
Arrays.asList(HttpMethod.GET.toString(), HttpMethod.POST.toString(), HttpMethod.DELETE.toString()));
configuration.setMaxAge(Duration.ofMillis(3600));
configuration.setAllowedHeaders(
Arrays.asList(HttpHeaders.AUTHORIZATION, HttpHeaders.CONTENT_TYPE, HttpHeaders.ACCEPT));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}