How can i access request headers in graphql query using java datafetcher environment?

Viewed 274

I want to fetch a header value I am passing during a GraphQl Query call. Something like we can do prior in case of rest api HttpServletRequest.getheader()

I wanted to fetch it from the dataFetchingEnvironment but the context fetched from this value did not get me any means to fetch the header values from request.

        try {
            GraphQLContext context =  env.getGraphQlContext();
            String Id= context.getHeader("headerkeyIpass"); 
// I know this method does not exist i am trying to paint a picture as to what i am asking

I do not intend to change the resolver method calls but any inputs to improve my code would be great.

2 Answers

The GraphQLContext has method getHttpServletRequest() which returns

java.util.Optional<javax.servlet.http.HttpServletRequest> 

So from there u can get the headers

GraphQLContext context =  env.getGraphQlContext();
HttpServletRequest request = context.getHttpServletRequest().get();
String Id= request.getHeader("headerkeyIpass"); 

If you are using the latest graphql libraries there are some breaking changed and you can get the headers from GraphQLServletContext as shown here

GraphQLServletContext graphQLServletContext = (GraphQLServletContext) env.getContext();
    
String user = graphQLServletContext.getHttpServletRequest().getHeader("user");

Like you said getHttpServletRequest does not exist on DataFetchingEnvironment.getGraphQlContext() when using the new official Spring 2.7 spring-boot-starter-graphql (not the legacy GraphQL Java Kickstart ones).

Instead you can add an autowired HttpServletRequest request variable at the top of your controller and inside each query resolver it will be filled with the request context.

@Controller
public class MyGraphQLController {
    ...

    @Autowired
    HttpServletRequest request;

    ...

    @QueryResolver(...)
    public XXX yyyy() {
        ...
        try {
            String Id= request.getHeader("headerkeyIpass"); 
        ...
    }
}
Related