现在前后端分离结构下,后端采用springcloud,前端post的数据通常采用json格式。而网关采用springcloudgateway。
工作需要要在springcloudgateway对前端接入的api请求,如果post的json对象,固定插入字段,比如插入sessionid,认证完成后插入userid。
这个就需要修改ServerHttpRequest里的body。最简单的处理方式肯定是在GlobalFilter里做修改。
网上查了很多方法,感觉都不是很好。
后来发现,springcloudgateway自带的gatewayFilter里有一个就是modifyRequestBody,它这个函数就可以修改请求体的内容。但是modifyRequestBody只能应用到route上。考虑到gatewayFilter和GlobalFilter大同小异。所以只要查到modifyRequestBody这个gatewayFilter的方法,就能应用到GlobalFilter来实现就行了。果然代码也不多。
直接上代码。
@Component
public class InsertBodyGlobalFilter implements GlobalFilter, Ordered {
private final List<HttpMessageReader<?>> messageReaders = HandlerStrategies.withDefaults().messageReaders();
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerRequest serverRequest = ServerRequest.create(exchange, messageReaders);
Config config = new Config();
config.setInClass(Map.class);
config.setOutClass(Map.class);
Class inClass = config.getInClass();
Class outClass = config.getOutClass();
config.setRewriteFunction(inClass, outClass, new BodyRewrite());
// TODO: flux or mono
Mono<?> modifiedBody = serverRequest.bodyToMono(inClass)
.flatMap(originalBody -> config.getRewriteFunction().apply(exchange, originalBody))
.switchIfEmpty(Mono.defer(() -> (Mono) config.getRewriteFunction().apply(exchange, null)));
BodyInserter bodyInserter = BodyInserters.fromPublisher(modifiedBody, config.getOutClass());
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);
// if the body is changing content types, set it here, to the bodyInserter
// will know about it
if (config.getContentType() != null) {
headers.set(HttpHeaders.CONTENT_TYPE, config.getContentType());
}
CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage(exchange, headers);
return bodyInserter.insert(outputMessage, new BodyInserterContext())
// .log("modify_request", Level.INFO)
.then(Mono.defer(() -> {
ServerHttpRequest decorator = decorate(exchange, headers, outputMessage);
return chain.filter(exchange.mutate().request(decorator).build());
}));
}
/**
* 优先级,order越大,优先级越低
*
* @return
*/
@Override
public int getOrder() {
return 0;
}
ServerHttpRequestDecorator decorate(ServerWebExchange exchange, HttpHeaders headers,
CachedBodyOutputMessage outputMessage) {
return new ServerHttpRequestDecorator(exchange.getRequest()) {
@Override
public HttpHeaders getHeaders() {
long contentLength = headers.getContentLength();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.putAll(headers);
if (contentLength > 0) {
httpHeaders.setContentLength(contentLength);
} else {
// TODO: this causes a 'HTTP/1.1 411 Length Required' // on
// httpbin.org
httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked");
}
return httpHeaders;
}
@Override
public Flux<DataBuffer> getBody() {
return outputMessage.getBody();
}
};
}
private class BodyRewrite implements RewriteFunction<Map, Map> {
@SuppressWarnings("unchecked")
@Override
public Publisher<Map> apply(ServerWebExchange t, Map u) {
// TODO Auto-generated method stub
//在这里添加插入的数据
u.put("userid", 4356);
return Mono.just(u);
}
}
}
网友评论