文章目录[隐藏]
- 拦截并修改body内容
拦截并修改body内容
代码语言:javascript复制@Resource
private ObjectMapper objectMapper;
private final List<HttpMessageReader<?>> messageReaders;
public PasswordDecoderGatewayFilterFactory() {
super(ModifyRequestBodyGatewayFilterFactory.Config.class);
this.messageReaders = HandlerStrategies.withDefaults().messageReaders();
}
public PasswordDecoderGatewayFilterFactory(
List<HttpMessageReader<?>> messageReaders) {
super(ModifyRequestBodyGatewayFilterFactory.Config.class);
this.messageReaders = messageReaders;
}
@Deprecated
public PasswordDecoderGatewayFilterFactory(ServerCodecConfigurer codecConfigurer) {
this(codecConfigurer.getReaders());
}
@Override
public GatewayFilter apply(Object config) {
return (exchange, chain) -> {
ServerRequest serverRequest = ServerRequest.create(exchange, messageReaders);
System.out.println(serverRequest.uri().getPath());
// 不是登录请求,直接向下执行
if (!StrUtil.containsAnyIgnoreCase(serverRequest.uri().getPath(), GatewayConstant.OAUTH_TOKEN_URL)) {
return chain.filter(exchange);
}
// 刷新token,直接向下执行
String grantType = serverRequest.queryParams().getFirst(GatewayConstant.TOKEN_TYPE);
if (StrUtil.equals(GatewayConstant.REFRESH_TOKEN, grantType)) {
return chain.filter(exchange);
}
// 终端设置不校验, 直接向下执行
try {
//校验验证码
checkCode(serverRequest);
MediaType mediaType = exchange.getRequest().getHeaders().getContentType();
Mono<String> modifiedBody = serverRequest.bodyToMono(String.class)
.flatMap(body -> {
if (MediaType.APPLICATION_JSON.isCompatibleWith(mediaType)) {
// 原body
JSONObject bodyMap = new JSONObject(body);
// 进行解密
SymmetricCrypto aes = SecureUtil.aes(ENCODE_KEY.getBytes(StandardCharsets.UTF_8));
log.debug("[password]:{}",bodyMap.get(PASSWORD));
String password = java.net.URLDecoder.decode(bodyMap.get(PASSWORD).toString(), StandardCharsets.UTF_8);
password = aes.decryptStr(Base64.decode(password.getBytes()), CharsetUtil.CHARSET_UTF_8);
bodyMap.put(PASSWORD,password);
log.debug("[password]:{}",password);
return Mono.just(encodeBody(bodyMap) );
}
return Mono.empty();
});
BodyInserter<Mono<String>, ReactiveHttpOutputMessage> bodyInserter = BodyInserters.fromPublisher(modifiedBody, String.class);
HttpHeaders headers = new HttpHeaders();
headers.putAll(exchange.getRequest().getHeaders());
// the new content type will be computed by bodyInserter
// and then set in the request decorator
headers.remove(HttpHeaders.CONTENT_LENGTH);
CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage(exchange, headers);
return bodyInserter.insert(outputMessage, new BodyInserterContext())
.then(Mono.defer(() -> {
ServerHttpRequestDecorator decorator = new ServerHttpRequestDecorator(
exchange.getRequest()) {
@Override
public HttpHeaders getHeaders() {
long contentLength = headers.getContentLength();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.putAll(super.getHeaders());
httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
if (contentLength > 0) {
httpHeaders.setContentLength(contentLength);
} else {
httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked");
}
return httpHeaders;
}
@Override
public Flux<DataBuffer> getBody() {
return outputMessage.getBody();
}
};
return chain.filter(exchange.mutate().request(decorator).build());
}));
} catch (Exception e) {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.PRECONDITION_REQUIRED);
try {
return response.writeWith(Mono.just(response.bufferFactory()
.wrap(objectMapper.writeValueAsBytes(
R.failed(e.getMessage())))));
} catch (JsonProcessingException e1) {
log.error("对象输出异常", e1);
}
}
return chain.filter(exchange);
};
}
base64 =变为==
代码语言:javascript复制String base = java.net.URLDecoder.decode(bodyMap.get(base64).toString(), StandardCharsets.UTF_8);