springweb flux拦截请求获取参数和方法做接口签名防重放校验

在给spring webflux做接口签名、防重放的时候,往往需要获取请求参数,请求方法等,而spring webflux无法像spring mvc那样好获取,这里根据之前的实践特地说明一下:

总体思路:
1、利用过滤器,从原request中获取到信息后,缓存在一个上下文对象中,然后构造新的request,传入后面的过滤器。因为原request流式的,用过一次后便无法再取参数了。
2、通过exchange的Attributes传递上下文对象,在不同的过滤器中使用即可。

1、上下文对象

@Getter
@Setter
@ToString
public class GatewayContext {public static final String CACHE_GATEWAY_CONTEXT = "cacheGatewayContext";/*** cache requestMethod*/private String requestMethod;/*** cache queryParams*/private MultiValueMap<String, String> queryParams;/*** cache json body*/private String requestBody;/*** cache Response Body*/private Object responseBody;/*** request headers*/private HttpHeaders requestHeaders;/*** cache form data*/private MultiValueMap<String, String> formData;/*** cache all request data include:form data and query param*/private MultiValueMap<String, String> allRequestData = new LinkedMultiValueMap<>(0);private byte[] requestBodyBytes;}

2、在过滤器中获取请求参数、请求方法。
这里我们只对application/jsonapplication/x-www-form-urlencoded这种做body参数拦截,而对于其他的请求,则可以通过url直接获取到query参数。

@Slf4j
@Component
public class GatewayContextFilter implements WebFilter, Ordered {/*** default HttpMessageReader*/private static final List<HttpMessageReader<?>> MESSAGE_READERS = HandlerStrategies.withDefaults().messageReaders();@Overridepublic Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {ServerHttpRequest request = exchange.getRequest();GatewayContext gatewayContext = new GatewayContext();HttpHeaders headers = request.getHeaders();gatewayContext.setRequestHeaders(headers);gatewayContext.getAllRequestData().addAll(request.getQueryParams());gatewayContext.setRequestMethod(request.getMethodValue().toUpperCase());gatewayContext.setQueryParams(request.getQueryParams());/** save gateway context into exchange*/exchange.getAttributes().put(GatewayContext.CACHE_GATEWAY_CONTEXT, gatewayContext);MediaType contentType = headers.getContentType();if (headers.getContentLength() > 0) {if (MediaType.APPLICATION_JSON.equals(contentType)) {return readBody(exchange, chain, gatewayContext);}if (MediaType.APPLICATION_FORM_URLENCODED.equalsTypeAndSubtype(contentType)) {return readFormData(exchange, chain, gatewayContext);}}String path = request.getPath().value();if (!"/".equals(path)) {log.info("{} Gateway context is set with {}-{}", path, contentType, gatewayContext);}return chain.filter(exchange);}@Overridepublic int getOrder() {return Integer.MIN_VALUE + 1;}/*** ReadFormData*/private Mono<Void> readFormData(ServerWebExchange exchange, WebFilterChain chain, GatewayContext gatewayContext) {HttpHeaders headers = exchange.getRequest().getHeaders();return exchange.getFormData().doOnNext(multiValueMap -> {gatewayContext.setFormData(multiValueMap);gatewayContext.getAllRequestData().addAll(multiValueMap);log.debug("[GatewayContext]Read FormData Success");}).then(Mono.defer(() -> {Charset charset = headers.getContentType().getCharset();charset = charset == null ? StandardCharsets.UTF_8 : charset;String charsetName = charset.name();MultiValueMap<String, String> formData = gatewayContext.getFormData();/** formData is empty just return*/if (null == formData || formData.isEmpty()) {return chain.filter(exchange);}log.info("1. Gateway Context formData: {}", formData);StringBuilder formDataBodyBuilder = new StringBuilder();String entryKey;List<String> entryValue;try {/** repackage form data*/for (Map.Entry<String, List<String>> entry : formData.entrySet()) {entryKey = entry.getKey();entryValue = entry.getValue();if (entryValue.size() > 1) {for (String value : entryValue) {formDataBodyBuilder.append(URLEncoder.encode(entryKey, charsetName).replace("+", "%20").replace("*", "%2A").replace("%7E", "~")).append("=").append(URLEncoder.encode(value, charsetName).replace("+", "%20").replace("*", "%2A").replace("%7E", "~")).append("&");}} else {formDataBodyBuilder.append(URLEncoder.encode(entryKey, charsetName).replace("+", "%20").replace("*", "%2A").replace("%7E", "~")).append("=").append(URLEncoder.encode(entryValue.get(0), charsetName).replace("+", "%20").replace("*", "%2A").replace("%7E", "~")).append("&");}}} catch (UnsupportedEncodingException e) {log.error("GatewayContext readFormData error {}", e.getMessage(), e);}/** 1. substring with the last char '&'* 2. if the current request is encrypted, substring with the start chat 'secFormData'*/String formDataBodyString = "";String originalFormDataBodyString = "";if (formDataBodyBuilder.length() > 0) {formDataBodyString = formDataBodyBuilder.substring(0, formDataBodyBuilder.length() - 1);originalFormDataBodyString = formDataBodyString;}/** get data bytes*/byte[] bodyBytes = formDataBodyString.getBytes(charset);int contentLength = bodyBytes.length;gatewayContext.setRequestBodyBytes(originalFormDataBodyString.getBytes(charset));HttpHeaders httpHeaders = new HttpHeaders();httpHeaders.putAll(exchange.getRequest().getHeaders());httpHeaders.remove(HttpHeaders.CONTENT_LENGTH);/** in case of content-length not matched*/httpHeaders.setContentLength(contentLength);/** use BodyInserter to InsertFormData Body*/BodyInserter<String, ReactiveHttpOutputMessage> bodyInserter = BodyInserters.fromObject(formDataBodyString);CachedBodyOutputMessage cachedBodyOutputMessage = new CachedBodyOutputMessage(exchange, httpHeaders);log.info("2. GatewayContext Rewrite Form Data :{}", formDataBodyString);return bodyInserter.insert(cachedBodyOutputMessage, new BodyInserterContext()).then(Mono.defer(() -> {ServerHttpRequestDecorator decorator = new ServerHttpRequestDecorator(exchange.getRequest()) {@Overridepublic HttpHeaders getHeaders() {return httpHeaders;}@Overridepublic Flux<DataBuffer> getBody() {return cachedBodyOutputMessage.getBody();}};return chain.filter(exchange.mutate().request(decorator).build());}));}));}/*** ReadJsonBody*/private Mono<Void> readBody(ServerWebExchange exchange, WebFilterChain chain, GatewayContext gatewayContext) {return DataBufferUtils.join(exchange.getRequest().getBody()).flatMap(dataBuffer -> {/** read the body Flux<DataBuffer>, and release the buffer* when SpringCloudGateway Version Release To G.SR2,this can be update with the new version's feature* see PR https://github.com/spring-cloud/spring-cloud-gateway/pull/1095*/byte[] bytes = new byte[dataBuffer.readableByteCount()];dataBuffer.read(bytes);DataBufferUtils.release(dataBuffer);gatewayContext.setRequestBodyBytes(bytes);Flux<DataBuffer> cachedFlux = Flux.defer(() -> {DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);DataBufferUtils.retain(buffer);return Mono.just(buffer);});/** repackage ServerHttpRequest*/ServerHttpRequest mutatedRequest = new ServerHttpRequestDecorator(exchange.getRequest()) {@Overridepublic Flux<DataBuffer> getBody() {return cachedFlux;}};ServerWebExchange mutatedExchange = exchange.mutate().request(mutatedRequest).build();return ServerRequest.create(mutatedExchange, MESSAGE_READERS).bodyToMono(String.class).doOnNext(objectValue -> {gatewayContext.setRequestBody(objectValue);if (objectValue != null && !objectValue.trim().startsWith("{")) {return;}try {gatewayContext.getAllRequestData().setAll(JsonUtil.fromJson(objectValue, Map.class));} catch (Exception e) {log.warn("Gateway context Read JsonBody error:{}", e.getMessage(), e);}}).then(chain.filter(mutatedExchange));});}}

3、签名、防重放校验
这里我们从上下文对象中取出参数即可
签名算法逻辑:
在这里插入图片描述

@Slf4j
@Component
public class GatewaySignCheckFilter implements WebFilter, Ordered {@Value("${api.rest.prefix}")private String apiPrefix;@Autowiredprivate RedisUtil redisUtil;//前后端约定签名密钥private static final String API_SECRET = "secret-xxx";@Overridepublic int getOrder() {return Integer.MIN_VALUE + 2;}@NotNull@Overridepublic Mono<Void> filter(ServerWebExchange exchange, @NotNull WebFilterChain chain) {ServerHttpRequest request = exchange.getRequest();String uri = request.getURI().getPath();GatewayContext gatewayContext = (GatewayContext) exchange.getAttributes().get(GatewayContext.CACHE_GATEWAY_CONTEXT);HttpHeaders headers = gatewayContext.getRequestHeaders();MediaType contentType = headers.getContentType();log.info("check url:{},method:{},contentType:{}", uri, gatewayContext.getRequestMethod(), contentType == null ? "" : contentType.toString());//如果contentType为空,只能是get请求if (contentType == null || StringUtils.isBlank(contentType.toString())) {if (request.getMethod() != HttpMethod.GET) {throw new RuntimeException("非法访问");}checkSign(uri, gatewayContext, exchange);} else {if (MediaType.APPLICATION_JSON.equals(contentType) || MediaType.APPLICATION_FORM_URLENCODED.equalsTypeAndSubtype(contentType)) {checkSign(uri, gatewayContext, exchange);}}return chain.filter(exchange);}private void checkSign(String uri, GatewayContext gatewayContext, ServerWebExchange exchange) {//忽略掉的请求List<String> ignores = Lists.newArrayList("/open/**", "/open/login/params", "/open/image");for (String ignore : ignores) {ignore = apiPrefix + ignore;if (uri.equals(ignore) || uri.startsWith(ignore.replace("/**", "/"))) {log.info("check sign ignore:{}", uri);return;}}String method = gatewayContext.getRequestMethod();log.info("start check sign {}-{}", method, uri);HttpHeaders headers = gatewayContext.getRequestHeaders();log.info("headers:{}", JsonUtils.objectToJson(headers));String clientId = getHeaderAttr(headers, SystemSign.CLIENT_ID);String timestamp = getHeaderAttr(headers, SystemSign.TIMESTAMP);String nonce = getHeaderAttr(headers, SystemSign.NONCE);String sign = getHeaderAttr(headers, SystemSign.SIGN);checkTime(timestamp);checkOnce(nonce);String headerStr = String.format("%s=%s&%s=%s&%s=%s", SystemSign.CLIENT_ID, clientId,SystemSign.NONCE, nonce, SystemSign.TIMESTAMP, timestamp);String signSecret = API_SECRET;String queryUri = uri + getQueryParam(gatewayContext.getQueryParams());log.info("headerStr:{},signSecret:{},queryUri:{}", headerStr, signSecret, queryUri);String realSign = calculatorSign(clientId, queryUri, gatewayContext, headerStr, signSecret);log.info("sign:{}, realSign:{}", sign, realSign);if (!realSign.equals(sign)) {log.warn("wrong sign");throw new RuntimeException("Illegal sign");}}private String getQueryParam(MultiValueMap<String, String> queryParams) {if (queryParams == null || queryParams.size() == 0) {return StringUtils.EMPTY;}StringBuilder builder = new StringBuilder("?");for (Map.Entry<String, List<String>> entry : queryParams.entrySet()) {String key = entry.getKey();List<String> value = entry.getValue();builder.append(key).append("=").append(value.get(0)).append("&");}builder.deleteCharAt(builder.length() - 1);return builder.toString();}private String getHeaderAttr(HttpHeaders headers, String key) {List<String> values = headers.get(key);if (CollectionUtils.isEmpty(values)) {log.warn("GatewaySignCheckFilter empty header:{}", key);throw new RuntimeException("GatewaySignCheckFilter empty header:" + key);}String value = values.get(0);if (StringUtils.isBlank(value)) {log.warn("GatewaySignCheckFilter empty header:{}", key);throw new RuntimeException("GatewaySignCheckFilter empty header:" + key);}return value;}private String calculatorSign(String clientId, String queryUri, GatewayContext gatewayContext, String headerStr, String signSecret) {String method = gatewayContext.getRequestMethod();byte[] bodyBytes = gatewayContext.getRequestBodyBytes();if (bodyBytes == null) {//空白的md5固定为:d41d8cd98f00b204e9800998ecf8427ebodyBytes = new byte[]{};}String bodyMd5 = UaaSignUtils.getMd5(bodyBytes);String ori = String.format("%s\n%s\n%s\n%s\n%s\n", method, clientId, headerStr, queryUri, bodyMd5);log.info("clientId:{},signSecret:{},headerStr:{},bodyMd5:{},queryUri:{},ori:{}", clientId, signSecret, headerStr, bodyMd5, queryUri, ori);return UaaSignUtils.sha256HMAC(ori, signSecret);}private void checkOnce(String nonce) {if (StringUtils.isBlank(nonce)) {log.warn("GatewaySignCheckFilter checkOnce Illegal");}String key = "api:auth:" + nonce;int fifteenMin = 60 * 15 * 1000;Boolean succ = redisUtil.setNxWithExpire(key, "1", fifteenMin);if (succ == null || !succ) {log.warn("GatewaySignCheckFilter checkOnce Repeat");throw new RuntimeException("checkOnce Repeat");}}private void checkTime(String timestamp) {long time;try {time = Long.parseLong(timestamp);} catch (Exception ex) {log.error("GatewaySignCheckFilter checkTime error:{}", ex.getMessage(), ex);throw new RuntimeException("checkTime error");}long now = DateTimeUtil.now();log.info("now: {}, time: {}", DateTimeUtil.millsToStr(now), DateTimeUtil.millsToStr(time));int fiveMinutes = 60 * 5 * 1000;long duration = now - time;if (duration > fiveMinutes || (-duration) > fiveMinutes) {log.warn("GatewaySignCheckFilter checkTime Late");throw new RuntimeException("checkTime Late");}}public interface SystemSign {/*** 客户端ID:固定值,由后端给前端颁发约定*/String CLIENT_ID = "client-id";/*** 客户端计算出的签名*/String SIGN = "sign";/*** 时间戳*/String TIMESTAMP = "timestamp";/*** 唯一值*/String NONCE = "nonce";}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/125803.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

关于CSS的几种字体悬浮的设置方法

关于CSS的几种字体悬浮的设置方法 1. 鼠标放上动态的2. 静态的&#xff08;位置看上悬浮&#xff09;2.1 参考QQ邮箱2.2 参考知乎 1. 鼠标放上动态的 效果如下&#xff1a; 代码如下&#xff1a; <!DOCTYPE html> <html lang"en"> <head><met…

<多线程章节八> 单例模式中的饿汉模式与懒汉模式的讲解,以及懒汉模式中容易引起的Bug

&#x1f490;专栏导读 本篇文章收录于多线程&#xff0c;也欢迎翻阅博主的其他文章&#xff0c;可能也会让你有不一样的收获&#x1f604; &#x1f337;JavaSE &#x1f342;多线程 &#x1f33e;数据结构 文章目录 &#x1f490;专栏导读&#x1f4a1;饿汉模式&#x1f4a1;…

从 Seq2Seq 到 Attention:彻底改变序列建模

探究Attention机制和意力的起源。 简介 在这篇博文[1]中&#xff0c;将讨论注意力机制的起源&#xff0c;然后介绍第一篇将注意力用于神经机器翻译的论文。由于上下文压缩、短期记忆限制和偏差&#xff0c;具有 2 个 RNN 的 Seq2Seq 模型失败了。该模型的 BLEU 分数随着序列长度…

【VPX630】青翼 基于KU115 FPGA+C6678 DSP的6U VPX通用超宽带实时信号处理平台

板卡概述 VPX630是一款基于6U VPX总线架构的高速信号处理平台&#xff0c;该平台采用一片Xilinx的Kintex UltraScale系列FPGA&#xff08;XCKU115&#xff09;作为主处理器&#xff0c;完成复杂的数据采集、回放以及实时信号处理算法。采用一片带有ARM内核的高性能嵌入式处理器…

【深度学习】pytorch——快速入门

笔记为自我总结整理的学习笔记&#xff0c;若有错误欢迎指出哟~ pytorch快速入门 简介张量&#xff08;Tensor&#xff09;操作创建张量向量拷贝张量维度张量加法函数名后面带下划线 _ 的函数索引和切片Tensor和Numpy的数组之间的转换张量&#xff08;tensor&#xff09;与标量…

三十九、CANdelaStudio实践-19服务(ReadDTCInformation)

本专栏将由浅入深的展开诊断实际开发与测试的数据库编辑,包含大量实际开发过程中的步骤、使用技巧与少量对Autosar标准的解读。希望能对大家有所帮助,与大家共同成长,早日成为一名车载诊断、通信全栈工程师。 本文介绍CANdelaStudio的19服务(ReadDTCInformation)编辑,欢迎…

基于STM32C8T6的智能蓝牙小车控制设计

**单片机设计介绍&#xff0c;1655基于STM32C8T6的智能蓝牙小车控制设计 文章目录 一 概要二、功能设计设计思路 三、 软件设计五、 程序文档 六、 结论七、 文章目录 一 概要 基于STM32C8T6的智能蓝牙小车控制设计是基于STM32微控制器和蓝牙模块开发的一种小型智能车辆控制系统…

力扣刷题-队列-滑动窗口最大值

239. 滑动窗口最大值 给定一个数组 nums&#xff0c;有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。 返回滑动窗口中的最大值。 进阶&#xff1a; 在线性时间复杂度内解决此题&#xff1f; …

算法leetcode|86. 分隔链表(rust重拳出击)

文章目录 86. 分隔链表&#xff1a;样例 1&#xff1a;样例 2&#xff1a;提示&#xff1a; 分析&#xff1a;题解&#xff1a;rust&#xff1a;go&#xff1a;c&#xff1a;python&#xff1a;java&#xff1a; 86. 分隔链表&#xff1a; 给你一个链表的头节点 head 和一个特…

ubuntu 22.04 源码安装 apollo 8.0

对于其他的关于GPU的安装包需求&#xff0c;这里不再列出&#xff0c;因为我之前安装过&#xff0c;偷个懒就不写了&#xff0c;哈哈哈哈1, 安装docker 安装docker命令(这里的安装命令都是在docker官网,还有安装包)&#xff1a; 1&#xff0c; 设置docker的apt仓库 # Add Do…

IDEA 如何运行 SpringBoot 项目

步骤一&#xff1a;配置 Maven 第一步&#xff1a;用 IDEA 打开项目&#xff0c;准备配置 maven 环境 &#xff0c;当然如果本地没有提前配置好 maven&#xff0c;就用 IDEA 默认的配置即可 配置 maven 步骤 情况 1&#xff1a;如果本地没有配置过 maven&#xff0c;可以保持如…

Jetpack:025-Jetpack中的多点触控事件

文章目录 1. 概念介绍2. 使用方法2.1 缩放事件2.2 旋转事件2.3 平移事件2.4 综合事件 3. 示例代码4. 内容总结 我们在上一章回中介绍了Jetpack中滚动事件相关的内容&#xff0c;本章回中主要介绍 多点解控事件。闲话休提&#xff0c;让我们一起Talk Android Jetpack吧&#xf…

HTML基本概念:

HTML简介&#xff1a; 超文本标记语言&#xff08;英语&#xff1a;HyperText Markup Language&#xff0c;简称&#xff1a;HTML&#xff09;是一种用于创建网页的标准标记语言。 1&#xff09;、HTML 是用来描述网页的一种语言。 2&#xff09;、HTML 不是一种编程语言&am…

笔记本电脑搜索不到wifi6 无线路由器信号

路由器更换成wifi6 无线路由器后&#xff0c;手机能搜索到这个无线信号&#xff0c;但是笔记本搜索不到这个无线信号&#xff0c;后网上搜索后发现是无线网卡驱动问题&#xff0c;很多无线网卡使用的是Intel芯片&#xff0c;Intel就此发布了公告&#xff0c;升级驱动就可以彻底…

我和云栖有个约会

开端&#xff0c;似曾相识的云栖 2023年阿里云云栖大会在云栖小镇举办&#xff0c;云栖小镇&#xff1f;在2020年的时候&#xff0c;曾经来过这里参加竞赛。时隔三年&#xff0c;身份变换&#xff0c;以开发者的身份&#xff0c;收到阿里云开发者社区的邀请&#xff0c;正好有…

linux 报错

输入 pip install -U openmim报错 有可能是服务器在其他国家&#xff0c;需要手动设置 把这三行复制到~/.bashrc里 export http_proxyhttp://127.0.0.1:3128 export https_proxy${http_proxy} export ftp_proxy${http_proxy}source ~/.bashrc

第57篇-某钩招聘网站加密参数分析【2023-10-31】

声明:该专栏涉及的所有案例均为学习使用,严禁用于商业用途和非法用途,否则由此产生的一切后果均与作者无关!如有侵权,请私信联系本人删帖! 文章目录 一、前言二、网站分析1.X-S-HEADER参数2.请求参数data3.响应机密值data一、前言 网址: aHR0cHM6Ly93d3cubGFnb3UuY29t…

[NSSRound#6 Team]check(Revenge)

文章目录 考点tarfile文件覆盖漏洞&#xff08;CVE-2007-4559&#xff09;PIN码计算 解题过程非预期解预期解 考点 tarfile文件覆盖漏洞&#xff08;CVE-2007-4559&#xff09; Python 中 tarfile 模块中的extract、extractFile和extractall 函数中的目录遍历漏洞 允许 用户协…

`.NET Web`新人入门必学项目`EarthChat`

.NET Web新人入门必学项目EarthChat EarthChat是一个基于.NET 7的实战项目&#xff0c;EarthChat提供了很多的最佳实践&#xff0c;EarthChat的目标也是成为一个很多人都喜欢的大型聊天业务系统&#xff0c;并且将结合SKAI大模型进行打造智能业务系统&#xff0c;在EarthChat中…

Pytorch 文本情感分类案例

一共六个脚本,分别是: ①generateDictionary.py用于生成词典 ②datasets.py定义了数据集加载的方法 ③models.py定义了网络模型 ④configs.py配置一些参数 ⑤run_train.py训练模型 ⑥run_test.py测试模型 数据集https://download.csdn.net/download/Victor_Li_/88486959?spm1…