测试安全的graphql订阅

时间:2018-10-05 02:07:02

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

我正在尝试测试用于保护我的应用程序中的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",但我相信它并不是那么简单。

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

1 个答案:

答案 0 :(得分:0)

通过添加HTTP标头使我在GraphQL Playground中工作:

$value =~ s/,([^,]*$)/$1/