GraphQL + Springboot + Http Headers

Viewed 608

I'm using these graphql dependencies:

    "com.graphql-java-kickstart:graphql-spring-boot-starter:12.0.0",
    "com.graphql-java-kickstart:graphql-java-tools:12.0.0", 

And how can I get httpRequestHeaders from the DataFetchingEnvironment class. I see DataFetchingEnvironment.getContext() is deprecated is there any other alternative?

Current logic:

        GraphQLServletContext servletContext = env.getContext(); //deprecated

        GraphQLContext qlContext = env.getGraphQlContext(); // No httpRequest

        var httpRequest = servletContext.getHttpServletRequest();
3 Answers

You can do:

env.getGraphQlContext().get(HttpServletRequest.class).getHeader("header")

As of 12.0.0, environment.getGraphQLContext() is not supported. This lack of support is referenced in the project's github (https://github.com/graphql-java-kickstart/graphql-spring-boot/issues/808)

As of version 13.0.0, you can access the HttpServletRequest by using

HttpServletRequest httpServletRequest = environment.getGraphQlContext().get(HttpServletRequest.class);

If you need to use version 12.0.0, my suggestion would be to use a OncePerRequestFilter and store the header information you need in a ThreadLocal value. Just remember to clear that thread local value after the request has been processed. This will only work if you turn off "async mode" that the GraphQL library introduced in 11.0.0, as "async mode" processes the request filters and graphql resolvers in different threads.

Upgrade to 13.0.0 (or 14.0.0) and call

HttpServletRequest httpServletRequest = env.getGraphQlContext().get(HttpServletRequest.class);

This will give you and HttpServletRequest, from where you can call

private static Map<String, String> getHeadersFromRequest(HttpServletRequest httpServletRequest) {
        var mapOfHeaders = new HashMap<String, String>();

        Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                mapOfHeaders.put(headerName, httpServletRequest.getHeader(headerName));
            }
        }
        return mapOfHeaders;
    }

to return a list map of headers.

Related