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

本文主要是介绍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";}}

这篇关于springweb flux拦截请求获取参数和方法做接口签名防重放校验的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/322172

相关文章

Python中 try / except / else / finally 异常处理方法详解

《Python中try/except/else/finally异常处理方法详解》:本文主要介绍Python中try/except/else/finally异常处理方法的相关资料,涵... 目录1. 基本结构2. 各部分的作用tryexceptelsefinally3. 执行流程总结4. 常见用法(1)多个e

SpringBoot实现不同接口指定上传文件大小的具体步骤

《SpringBoot实现不同接口指定上传文件大小的具体步骤》:本文主要介绍在SpringBoot中通过自定义注解、AOP拦截和配置文件实现不同接口上传文件大小限制的方法,强调需设置全局阈值远大于... 目录一  springboot实现不同接口指定文件大小1.1 思路说明1.2 工程启动说明二 具体实施2

JavaScript中比较两个数组是否有相同元素(交集)的三种常用方法

《JavaScript中比较两个数组是否有相同元素(交集)的三种常用方法》:本文主要介绍JavaScript中比较两个数组是否有相同元素(交集)的三种常用方法,每种方法结合实例代码给大家介绍的非常... 目录引言:为什么"相等"判断如此重要?方法1:使用some()+includes()(适合小数组)方法2

SpringBoot 获取请求参数的常用注解及用法

《SpringBoot获取请求参数的常用注解及用法》SpringBoot通过@RequestParam、@PathVariable等注解支持从HTTP请求中获取参数,涵盖查询、路径、请求体、头、C... 目录SpringBoot 提供了多种注解来方便地从 HTTP 请求中获取参数以下是主要的注解及其用法:1

HTTP 与 SpringBoot 参数提交与接收协议方式

《HTTP与SpringBoot参数提交与接收协议方式》HTTP参数提交方式包括URL查询、表单、JSON/XML、路径变量、头部、Cookie、GraphQL、WebSocket和SSE,依据... 目录HTTP 协议支持多种参数提交方式,主要取决于请求方法(Method)和内容类型(Content-Ty

SpringBoot请求参数传递与接收示例详解

《SpringBoot请求参数传递与接收示例详解》本文给大家介绍SpringBoot请求参数传递与接收示例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋... 目录I. 基础参数传递i.查询参数(Query Parameters)ii.路径参数(Path Va

504 Gateway Timeout网关超时的根源及完美解决方法

《504GatewayTimeout网关超时的根源及完美解决方法》在日常开发和运维过程中,504GatewayTimeout错误是常见的网络问题之一,尤其是在使用反向代理(如Nginx)或... 目录引言为什么会出现 504 错误?1. 探索 504 Gateway Timeout 错误的根源 1.1 后端

使用Python的requests库来发送HTTP请求的操作指南

《使用Python的requests库来发送HTTP请求的操作指南》使用Python的requests库发送HTTP请求是非常简单和直观的,requests库提供了丰富的API,可以发送各种类型的HT... 目录前言1. 安装 requests 库2. 发送 GET 请求3. 发送 POST 请求4. 发送

MySQL 表空却 ibd 文件过大的问题及解决方法

《MySQL表空却ibd文件过大的问题及解决方法》本文给大家介绍MySQL表空却ibd文件过大的问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考... 目录一、问题背景:表空却 “吃满” 磁盘的怪事二、问题复现:一步步编程还原异常场景1. 准备测试源表与数据

python 线程池顺序执行的方法实现

《python线程池顺序执行的方法实现》在Python中,线程池默认是并发执行任务的,但若需要实现任务的顺序执行,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋... 目录方案一:强制单线程(伪顺序执行)方案二:按提交顺序获取结果方案三:任务间依赖控制方案四:队列顺序消