apollo-server-hapi授权验证回调未执行

时间:2019-08-18 08:28:26

标签: javascript graphql apollo-server hapi

试图在hapi中运行apollo服务器。我在hapi中具有有效的cookie授权,但是我无法控制对graphql的查询。在graphql查询中不会调用validateFunc。

使用http://localhost:8080/login登录后调用

validateFunc 但是对http://localhost:8080/graphql的查询不会调用validateFunc。 如果我将graphql的auth模式设置为required,我将不会收到未授权的错误,但validateFunc仍然不会被调用。

const Hapi = require("@hapi/hapi"); //v18.3.2
const { ApolloServer, gql } = require("apollo-server-hapi"); //v2.8.1

const typeDefs = gql`
  type Query {
    _: String
  }

  type Mutation {
    _: String
  }
`;

const resolvers = {
  Query: {},

  Mutation: {}
};

const runServer = async () => {
  const server = new Hapi.server({ port: 8080 });
  await server.register(require("@hapi/cookie"));
  server.auth.strategy("session", "cookie", {
    cookie: {
      name: "test-project",
      password:
        "long-long-password-long-long-password-long-long-password-long-long-password",
      isSecure: false
    },

    validateFunc: async (request, session) => {
      console.log("Why it is not called on graphql queries???");

      return { valid: true, credentials: "account" };
    }
  });

  server.auth.default("session");

  //GRAPH QL!
  const graphqlServer = new ApolloServer({
    typeDefs,
    resolvers,
    context: async function(q) {
      console.log("Graphql context was called!");
      return q;
    },
    introspection: false,
    playground: true,
    route: {
      options: {
        auth: {
          mode: "try"
        }
      }
    }
  });

  server.route([
    {
      method: "GET",
      path: "/login",
      handler: function(request, h) {
        request.cookieAuth.set({ id: "key" });

        return "LOGIN!";
      },
      options: {
        auth: {
          mode: "try"
        }
      }
    },
    {
      method: "GET",
      path: "/test",
      handler: function(request, h) {
        console.log("TEST");
        return "OK";
      },
      options: {
        auth: {
          mode: "try"
        }
      }
    }
  ]);

  await graphqlServer.applyMiddleware({
    app: server,
    route: {
      auth: { mode: "try" }
    }
  });

  await graphqlServer.installSubscriptionHandlers(server.listener);

  await server.start().then(() => {
    console.log(`?  Server ready at ${server.info.uri}/graphql `);
  });
};

runServer();

期望graphql查询执行hapi的validateFunc()

0 个答案:

没有答案