繁体   English   中英

如何从 spring 启动应用程序中的 graphQL 端点中的传入消息中读取请求标头

[英]How to read request headers from incoming message in a graphQL endpoint in spring boot application

我有一个 spring 启动应用程序运行一个 graphql 端点来验证和执行查询和突变,但是,我需要读取一个 header 以将其值传递给传入消息中的另一个端点。 graphql 中有没有办法读取这些值? 某种 getHeaders 或类似的东西?

GraphQL 本身并没有定义任何与如何通过网络公开它相关的东西,因此它没有定义任何与获取 HTTP 标头相关的东西。开发人员使用他们的方式。所以,这取决于你使用的底层技术通过 HTTP 提供 GraphQL。

考虑您使用graphql-spring-bootgraphql-java-tools ,并假设您没有自定义GraphQLContext ,您可以尝试将DataFetchingEnvironment参数添加到您的解析器函数,然后从中获取GraphQLContext 然后,您可以从上下文中获取HttpServletRequest并访问标头:

    public Foo resolveFoo(Map<String,String> input , DataFetchingEnvironment env){

        GraphQLContext context =  env.getContext();
        HttpServletRequest request = context.getHttpServletRequest().get();
        request.getHeader("content-type");
    }

@Ken Chan 的解决方案对我不起作用。 GraphQLContext没有名为getHttpServletRequest方法。
改用GraphQLServletContext解决了这个问题。 您可以将代码更改为:

public Foo resolveFoo(Map<String,String> input , DataFetchingEnvironment env){

    GraphQLServletContext context =  env.getContext();
    String header = context.getHttpServletRequest().getHeader("content-type");
}

显然,上下文的类型没有标准化。 我使用 SPQR,就我而言,我发现(通过调试):

        DefaultGlobalContext<ServletWebRequest> context = handlerParameters.getDataFetchingEnvironment().getContext();
        context.getNativeRequest().getHeader("something");

谷歌给我带来了这个答案,不幸的是它是针对 Spring 框架的。 许多人使用 Spring 框架,但如果你像我一样使用 Apache Tomcat 和 GraphQL 集成,你可以使用它。

        graphql.kickstart.servlet.context.DefaultGraphQLServletContext.DefaultGraphQLServletContext context =  dataFetchingEnvironment.getContext();
        jakarta.servlet.http.HttpServletRequest request = context.getHttpServletRequest();
        String tokenBearer = request.getHeader("Authorization");

不是对您的问题陈述的直接回答,但可以在请求到达解析器端点之前使用过滤器来处理它(如果这是必需的):

public class HeaderFilter implements Filter {

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
    final HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
    
    String headerVal= httpServletRequest.getHeader("<header string>");
    
    try {
        filterChain.doFilter(httpServletRequest, servletResponse);
    } catch (IOException | ServletException e) {
        //handle as you wish
    }
}

对于最新版本,这些答案太旧了。 您可以尝试在controller中自动连接一个 HttpServletRequest ,例如

@Slf4j
@Controller
public class YourQueryController {
@Autowired
private HttpServletRequest request;
....

然后执行以下逻辑得到header:

request.getHeader("Authorization")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM