Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to Validate a Specific Value in the Request Body of a POST Request in Spring Cloud Gateway MVC? #3512

Open
marinusgeuze opened this issue Sep 3, 2024 · 0 comments

Comments

@marinusgeuze
Copy link

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

    return route()
        .POST(
            “path”
            https())
        .before(validate())
        .build();
  }

Before filter

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;
}


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants