背景
往往项目中的开放接口可能被别有用心者对其进行抓包然后对请求参数进行篡改,或者重复请求占用系统资源为此我们行业内使用比较多的策略是接口签名校验。签名校验的实现可以用注解+aop的形式实现,也可以使用过滤器统一拦截校验实现,此篇文章博主将会介绍如何在过滤器中实现
思路
俗话说的好,要想干得好,脑子里得有明确的思路。博主以往的工作经历已经养成一个良好的习惯,任何需求编码前习惯先画出思维流程图
大致实现思路:
- 客户端 (参数+时间戳+随机串+密钥 )进行md5加密,将加密后的sign放在请求头里带到服务端
- 服务端在过滤器中获取请求头和请求体的数据
- 判断此次请求的时间戳和系统当前时间的偏移量是否大于1分钟(偏移时间量可以自行定义),如果大于可以判定为非法请求
- 把sign作为key查询缓存中是否存在,存在可以判定为重放请求
(**此步骤也可忽略,接入限流处理)**
- 服务端按照客户端同样的规则生成sign签名,(参数+时间戳+随机串+密钥 )进行md5加密,判断请求的sign签名和生成的sign是否一致,不一致可以判定为参数已经被篡改
- 当上面校验都通过后,可以把sign签名作为key存入缓存,方便下次判断请求是否重放(
**此步骤也可忽略,接入限流处理)**
- 放行请求
代码实现
package cn.jian.yuan.gateway;import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBufAllocator;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.NettyDataBuffer;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;import javax.print.DocFlavor;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;@Component
public class MyGatewayFilter implements GlobalFilter, Ordered {private RedisTemplate<String, Object> redisTemplate;private StringRedisTemplate stringRedisTemplate;@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {ServerHttpRequest request = exchange.getRequest();ServerHttpResponse response = exchange.getResponse();String sign = request.getHeaders().getFirst("sign");String timestamp = request.getHeaders().getFirst("timestamp");String nonce = request.getHeaders().getFirst("nonce");//直接放行的path集合List<String> releaserPathList = new ArrayList<>();releaserPathList.add("/*.html");releaserPathList.add("/**/*.js");String path = request.getURI().getPath();//直接放行的urlif (releaserPathList.contains(path)) {return chain.filter(exchange);}//判断必填参数if (StringUtils.isBlank(sign) || StringUtils.isBlank(timestamp) || StringUtils.isBlank(nonce)) {//自定义返回错误信息return returnResult(response, HttpStatus.BAD_REQUEST, "必填参数为空");}//判断请求发起时间和系统时间的偏移量if (Math.abs(System.currentTimeMillis()) - Long.parseLong(timestamp) > 60000L) {return returnResult(response, HttpStatus.REQUEST_TIMEOUT, "请求超时");}if (request.getMethodValue().equalsIgnoreCase(HttpPost.METHOD_NAME)) {/*--- 判断是否重放只在post请求里判断重放是因为博主认为get请求大部分都是查询,可以接入限流框架来处理并发。或者过滤器中直接不判断重放,全部由限流框架来处理*/if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(sign))) {return returnResult(response, HttpStatus.BAD_REQUEST, "请求重放");}String jsonBody = resolverBodyJsonRequest(request);if (!checkSign(timestamp, nonce, sign, jsonBody)) {return returnResult(response, HttpStatus.BAD_REQUEST, "非法请求");}//下面的将请求体再次封装会写到request里传到下一级,否则由于请求体已被消费,后续服务将取不到值ServerHttpRequest newRequest = request.mutate().uri(request.getURI()).build();DataBuffer dataBuffer = stringBuffer(jsonBody);Flux<DataBuffer> dataBufferFlux = Flux.just(dataBuffer);request = new ServerHttpRequestDecorator(newRequest) {@Overridepublic Flux<DataBuffer> getBody() {return dataBufferFlux;}};//有效期和上面请求时间偏移量保持一致redisTemplate.opsForValue().set(sign, "1", 60000L, TimeUnit.MILLISECONDS);} else if (request.getMethodValue().equalsIgnoreCase(HttpGet.METHOD_NAME)) {StringBuilder builder = new StringBuilder();MultiValueMap<String, String> queryParams = request.getQueryParams();for (Map.Entry<String, List<String>> entry : queryParams.entrySet()) {String key = entry.getKey();List<String> value = entry.getValue();builder.append("{\"").append(key).append("\":\"").append(value.get(0)).append("\"}");}if(!checkSign(timestamp, nonce, sign, builder.toString())){return returnResult(response, HttpStatus.BAD_REQUEST, "非法请求");}}return chain.filter(exchange.mutate().request(request).build());}private DataBuffer stringBuffer(String jsonBody) {byte[] bytes = jsonBody.getBytes(StandardCharsets.UTF_8);NettyDataBufferFactory nettyDataBufferFactory = new NettyDataBufferFactory(ByteBufAllocator.DEFAULT);NettyDataBuffer nettyDataBuffer = nettyDataBufferFactory.allocateBuffer(bytes.length);return nettyDataBuffer.write(bytes);}//参数拼接后进行md5加密对比private boolean checkSign(String timestamp, String nonce, String sign, String jsonBody) {//注意参数拼接顺序和数据类型要和前端保持一致,否则加密出来的结果不一样TreeMap map = JSON.parseObject(jsonBody, TreeMap.class);map.put("timestamp", timestamp);map.put("nonce", nonce);map.put("secret", "自定义密钥key");//不能泄漏,自己在代码中定义好即可String jsonString = JSON.toJSONString(map);String localSign = DigestUtils.md5DigestAsHex(jsonString.getBytes(StandardCharsets.UTF_8));return localSign.equals(sign);}//gateway 网关过滤器获取请求体json数据的方法private String resolverBodyJsonRequest(ServerHttpRequest request) {Flux<DataBuffer> body = request.getBody();AtomicReference<Object> reference = new AtomicReference<>();body.subscribe(dataBuffer -> {CharBuffer decode = StandardCharsets.UTF_8.decode(dataBuffer.asByteBuffer());DataBufferUtils.release(dataBuffer);reference.set(decode.toString());});return reference.get().toString();}private Mono<Void> returnResult(ServerHttpResponse response, HttpStatus httpStatus, String msg) {DataBuffer dataBuffer = response.bufferFactory().wrap(msg.trim().getBytes());response.getHeaders().add("content-type", "application/json;charset=UTF-8");response.setStatusCode(httpStatus);return response.writeWith(Mono.just(dataBuffer));}@Overridepublic int getOrder() {return -100;}
}
以上就完成了在Gateway 网关过滤器中完成了对接口的签名检验功能