首页 > 解决方案 > 测试安全的 graphql 订阅

问题描述

我正在尝试测试用于在我的应用程序中保护 graphql 订阅的配置。

这是我在ApolloServer构造函数中的配置:

  const app = express();

  const jwt_authentication = jwt({
    secret: JWT_SECRET,
    credentialsRequired: false
  })

  const server = new ApolloServer({
    typeDefs,
    resolvers,
    introspection: true,
    playground: true,
    formatError: error => {
      console.log(error);
    },
    context: async ({req, connection }) => {
      if (connection) {
        return connection.context;
      } else {
        return some_method_to_return_user_info;
      }
    },
    subscriptions: {
      onConnect: async (connectionParams, webSocket, context) => {
        const user = await jsonwebtoken.verify(connectionParams.jwt, JWT_SECRET);

        const userInfo= some_method_to_return_user_info;
        if (userInfo) {
           return { user: userInfo };
        }

        throw new Error("Unauthorized subscription");
      }
    }
  });

  app.use(GRAPHQL_PATH, jwt_authentication);
  //...

当我在 GraphQL Playground 中运行订阅时,出现错误:

jwt must be provided

我先用 header"Authorization": "Bearer MY_TOKEN"再用进行测试"jwt": "MY_TOKEN",但我相信它没有那么简单。

是否有可能在不实现客户端代码的情况下测试我的订阅?

标签: node.jsexpressgraphqlapollo-servergraphql-subscriptions

解决方案


我通过以这种方式添加 HTTP 标头使其在 GraphQL Playground 中工作:

{
  "jwt": "MY_TOKEN"
}

推荐阅读