You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In our Spring Cloud Gateway MVC project, we need to validate a specific value in the request body of a POST request before routing it to a downstream microservice.
The only solution we've found that works is the code snippet below. However, it feels somewhat cumbersome, and we're wondering if there's a cleaner, more idiomatic way to achieve this. We couldn't find a better approach in the Spring Cloud Gateway MVC documentation.
public static Function<ServerRequest, ServerRequest> validate() {
return request -> {
try {
var clonedInputStream = cloneInputStream(request);
var clonedRequest = adaptCachedBody().apply(request);
Map<String, String> jsonRequest = new ObjectMapper().readValue(clonedInputStream, Map.class);
// Reset stream so that it can be read again when request is routed to downstream MicroService
clonedInputStream.reset();
var field = jsonRequest.get("field");
//Validate logic
return clonedRequest;
} catch (IOException e) {
throw new RuntimeException(e);
}
};
}
private static InputStream cloneInputStream(ServerRequest request) throws IOException {
var inputStream = request.servletRequest().getInputStream();
var byteArray = StreamUtils.copyToByteArray(inputStream);
var clonedInputStream = new ByteArrayInputStream(byteArray);
// This attribute is read by the adaptCachedBody function
request.attributes().put(MvcUtils.CACHED_REQUEST_BODY_ATTR, clonedInputStream);
return clonedInputStream;
}
The text was updated successfully, but these errors were encountered:
Hi,
In our Spring Cloud Gateway MVC project, we need to validate a specific value in the request body of a POST request before routing it to a downstream microservice.
The only solution we've found that works is the code snippet below. However, it feels somewhat cumbersome, and we're wondering if there's a cleaner, more idiomatic way to achieve this. We couldn't find a better approach in the Spring Cloud Gateway MVC documentation.
Could anyone suggest a more elegant solution?
Thanks in advance for your help!
Router configuration
Before filter
The text was updated successfully, but these errors were encountered: