| | |
| | | import org.springframework.core.io.buffer.*; |
| | | import org.springframework.http.HttpHeaders; |
| | | import org.springframework.http.HttpMethod; |
| | | import org.springframework.http.MediaType; |
| | | import org.springframework.http.server.reactive.ServerHttpRequest; |
| | | import org.springframework.http.server.reactive.ServerHttpRequestDecorator; |
| | | import org.springframework.stereotype.Component; |
| | | import org.springframework.web.server.ServerWebExchange; |
| | | import reactor.core.publisher.Flux; |
| | | import reactor.core.publisher.Mono; |
| | | |
| | | import java.nio.charset.StandardCharsets; |
| | | |
| | | /** |
| | | * 跨站脚本过滤器 |
| | |
| | | if(method != HttpMethod.POST){ |
| | | return chain.filter(exchange); |
| | | } |
| | | String contentType = request.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE); |
| | | // multipart(二进制)请求禁止读取/重写body,否则会导致文件内容损坏 |
| | | if (StringUtils.isNotEmpty(contentType) && StringUtils.startsWithIgnoreCase(contentType, "multipart/")) { |
| | | return chain.filter(exchange); |
| | | } |
| | | // 非JSON请求不处理,避免误伤其他content-type |
| | | if (!isJsonContentType(contentType)) { |
| | | return chain.filter(exchange); |
| | | } |
| | | ServerHttpRequestDecorator httpRequestDecorator = requestDecorator(exchange); |
| | | return chain.filter(exchange.mutate().request(httpRequestDecorator).build()); |
| | | } |
| | | |
| | | |
| | | private boolean isJsonContentType(String contentType) { |
| | | if (StringUtils.isEmpty(contentType)) { |
| | | return false; |
| | | } |
| | | if (StringUtils.startsWithIgnoreCase(contentType, MediaType.APPLICATION_JSON_VALUE)) { |
| | | return true; |
| | | } |
| | | // 兼容 application/*+json |
| | | return StringUtils.containsIgnoreCase(contentType, "+json"); |
| | | } |
| | | |
| | | |
| | | private ServerHttpRequestDecorator requestDecorator(ServerWebExchange exchange) { |
| | | ServerHttpRequestDecorator serverHttpRequestDecorator = new ServerHttpRequestDecorator(exchange.getRequest()) { |
| | |
| | | byte[] content = new byte[join.readableByteCount()]; |
| | | join.read(content); |
| | | DataBufferUtils.release(join); |
| | | String bodyStr = new String(content, StandardCharsets.UTF_8); |
| | | // 转成字节 |
| | | byte[] bytes = bodyStr.getBytes(); |
| | | NettyDataBufferFactory nettyDataBufferFactory = new NettyDataBufferFactory(ByteBufAllocator.DEFAULT); |
| | | DataBuffer buffer = nettyDataBufferFactory.allocateBuffer(bytes.length); |
| | | buffer.write(bytes); |
| | | DataBuffer buffer = nettyDataBufferFactory.allocateBuffer(content.length); |
| | | buffer.write(content); |
| | | return buffer; |
| | | }); |
| | | } |