问题:Gateway Security配置白名单后,客户请求白名单接口但是url上拼了不可用的token,导致报错文章来源:https://www.toymoban.com/news/detail-512857.html
解决:校验是否符合白名单接口,然后将请求头的Authorization和url中的access_token移除文章来源地址https://www.toymoban.com/news/detail-512857.html
http.addFilterAt((WebFilter) (exchange, chain) -> {
ServerHttpRequest request = exchange.getRequest();
String access_token = request.getQueryParams().getFirst("access_token");
for (String ignored : permitUrlProperties.getIgnored()) {
//匹配白名单路径
if (pathMatcher.match(ignored, exchange.getRequest().getPath().value())) {
//如果请求白名单接口,则移除Authorization的数据
ServerHttpRequest authorization = exchange.getRequest().mutate().headers(httpHeaders ->
httpHeaders.remove("Authorization")
).build();
//移除请求头,如果不.build()则是在原request上移除
exchange.mutate().request(authorization);
//如果请求白名单接口,queryParam还传入token则移除
if(access_token!=null) {
MultiValueMap<String, String> queryParams = request.getQueryParams();
if(queryParams.containsKey("access_token")){
URI oldUri = request.getURI();
String oldRequestUrI = oldUri.toString();
String oldRequestUrl = oldRequestUrI.substring(0,oldRequestUrI.indexOf("?"));
StringBuffer stringBuffer = new StringBuffer(oldRequestUrl);
String strparam = oldRequestUrI.substring(oldRequestUrI.indexOf("?")+1);
String[] split = strparam.split("&");
for (int i = 0 ; i < split.length ; i++){
String ssssss = split[i];
if (ssssss.contains("access_token")){
}else {
if(i == 0){
stringBuffer.append("?").append(ssssss);
}else {
stringBuffer.append("&").append(ssssss);
}
}
}
URI uri1 = URI.create(stringBuffer.toString());
ServerHttpRequest newRequest = request.mutate().uri(uri1).build();
ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
return chain.filter(newExchange);
}
}
}
}
if(access_token!=null) {
exchange.getRequest().mutate().headers(httpHeaders ->
httpHeaders.add(
"Authorization",
OAuth2AccessToken.BEARER_TYPE+" "+request.getQueryParams().getFirst("access_token"))
);
}
return chain.filter(exchange);
}, SecurityWebFiltersOrder.FIRST);
到了这里,关于ServerHttpRequest(ServerWebExchange)修改请求参数修改请求头的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!