1.yaml文件中配置白名单列表
# api网关增加白名单
whitelist:
urls:
- "/xxx/notice/**"
2.读取配置文件中的白名单列表
@Component
@ConfigurationProperties(prefix = "whitelist")
public class WhitelistConfig {
private Set<String> urls = new HashSet<>();
public Set<String> getUrls() {
return urls;
}
public void setUrls(Set<String> urls) {
this.urls = urls;
}
}
3.创建单例模式的AntPathMatcher,这个有多中方式,我们可以使用单例模式通过双重校验,通过new 来创建单例模式的AntPathMatcher,也可以利用spring对对象的管理来实现
@Configuration
public class AntPathMatcherHolder {
@Bean(name = "whiteUrlMatcher")
public AntPathMatcher antPathMatcher() {
return new AntPathMatcher();
}
}
4.应用,对进入网关的url进行验证如果是在白名单中,则不走认证鉴权逻辑,否则保持原有的鉴权校验逻辑
private boolean isInWhitelist(String url) {
//此处根据实际情况进行处理为实际的路径
LOGGER.info("白名单的url路径:****** {}",url);
String pattern = "/api/[^/]+/[^/]+(/.+)";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(url);
if(m.find()){
String targetPart = m.group(1);
Set<String> whitList = whitelistConfig.getUrls();
if(whitList.isEmpty()){
return false;
}
Iterator<String> iterator = whitList.iterator();
while (iterator.hasNext()) {
String pat = iterator.next();
if(antPathMatcher.match(pat, targetPart)){
return true;
}
}
}
return false;
}