Skip to content

Multipart body is missing #3959

@smdka

Description

@smdka

Hi, everyone!
I'm using Spring Cloud Gateway MVC 4.1.2
I need to validate incoming file in multipart request by checking his magic bytes.
Straight approach doesn't work because after opening a stream from a file it becomes unavailable for further filters. I tried to use caching but it doesn't work either, request body is missing downstream. Is there a workaround or maybe a right approach to do this kind of validation with Spring Cloud Gateway MVC?

Here's my code snippet:

@Bean
    public RouterFunction<ServerResponse> myRoute() {
        return route("gateway").POST(path("/upload"), http("http://localhost:8081")).before(request -> {
            var clonedInputStream = cacheBody(request);
            var clonedRequest = adaptCachedBody().apply(request);
            clonedInputStream.reset();

            try {
                byte[] pdfSignature = {0x25, 0x50, 0x44, 0x46, 0x2D};
                byte[] actualSignature = new byte[pdfSignature.length];
                HttpServletRequest httpServletRequest = request.servletRequest();
                Part file = httpServletRequest.getPart("file");
                file.getInputStream().read(actualSignature);
                if (!Arrays.equals(pdfSignature, actualSignature)) {
                    throw new RuntimeException("Not PDF");
                }
            } catch (IOException | ServletException e) {
                throw new RuntimeException(e);
            }
            return clonedRequest;
        }).build();
    }

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions