【问题标题】:Test a secure graphql subscription测试安全的 graphql 订阅
【发布时间】:2019-03-10 11:24:57
【问题描述】:

我正在尝试在我的应用程序中测试用于保护 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

我用标题"Authorization": "Bearer MY_TOKEN" 测试,然后用"jwt": "MY_TOKEN" 进行测试,但我相信它没有那么简单。

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

【问题讨论】:

    标签: node.js express graphql apollo-server graphql-subscriptions


    【解决方案1】:

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

    {
      "jwt": "MY_TOKEN"
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-20
      • 1970-01-01
      • 2017-09-19
      • 2019-12-02
      • 2021-10-09
      • 2020-11-17
      • 2021-03-17
      • 2019-01-19
      相关资源
      最近更新 更多