我有类似的问题,答案是肯定的。
这是我的解决方案(基于源头处理访问控制-允许-源)
1. 从“源”标头解析主机
// origin
String origin = request.getHeader("Origin");
URL originUrl = null;
try {
originUrl = new URL(origin);
} catch (MalformedURLException ex) {
}
// originUrl.getHost() -> Return the host need to be verified
2. 检查 originUrl.getHost()
// Allow myDomain.com
// Or anySubDomain.myDomain.com
// Or subSub.anySubDomain.myDomain.com
// hostAllowedPattern
Pattern hostAllowedPattern = Pattern.compile("(.+\\.)*myDomain\\.com", Pattern.CASE_INSENSITIVE);
// Allow host?
if (hostAllowedPattern.matcher(originUrl.getHost()).matches()) {
response.addHeader("Access-Control-Allow-Origin", origin);
} else {
// Throw 403 status OR send default allow
response.addHeader("Access-Control-Allow-Origin", "https://my_domain.com");
}
3. 结果:
// If 'origin': https://sub1.myDomain.com --> Matched
Access-Control-Allow-Origin: https://sub1.myDomain.com
// If 'origin': https://sub2.myDomain.com --> Matched
Access-Control-Allow-Origin: https://sub2.myDomain.com
// If 'origin': https://notAllowDomain.com --> Not Matched
Access-Control-Allow-Origin: https://my_domain.com
4. 其他:
You need to verify scheme & port too.