在spring cloud gateway中可以通过全局过滤器进行请求参数的过滤,以下是一个过滤xss攻击的实现代码:
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.GatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.HtmlUtils;
@Component
public class XssGatewayFilter implements GatewayFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
MultiValueMap<String, String> queryParams = request.getQueryParams();
MultiValueMap<String, String> formParams = null;
if (request.getMethod() == HttpMethod.POST) {
formParams = request.getFormData().block();
}
if (queryParams != null) {
queryParams.forEach((key, values) -> {
List<String> newValues = values.stream()
.map(HtmlUtils::htmlEscape)
.collect(Collectors.toList());
queryParams.put(key, newValues);
});
}
if (formParams != null) {
formParams.forEach((key, values) -> {
List<String> newValues = values.stream()
.map(HtmlUtils::htmlEscape)
.collect(Collectors.toList());
formParams.put(key, newValues);
});
}
return chain.filter(exchange);
}
}
在配置参数文件中增加以下配置:
spring:
cloud:
gateway:
routes:
- id: myroute
uri: http://localhost:8080
filters:
- XssGatewayFilter
核心思路是通过HtmlUtils::htmlEscape对请求参数内容进行转码处理来实现防止xss攻击。