Reactjs 阿波罗。如何在不进行jwt令牌检查的情况下允许登录/注册查询?

Reactjs 阿波罗。如何在不进行jwt令牌检查的情况下允许登录/注册查询?,reactjs,jwt,apollo,jwt-auth,Reactjs,Jwt,Apollo,Jwt Auth,如何在不进行jwt令牌检查的情况下允许登录/注册查询 我在Apollo中获取用于登录/注册查询的jwt令牌时遇到问题。我试图理解如何不检查jwt令牌的正确性以进行查询(突变)登录/注册。例如,对于我的应用程序中的第一次登录,我没有令牌,因此空字符串或null或undefined不正确,我不能调用查询登录/注册 我尝试在上下文中检查令牌 const getTokenPayload = async (token?: string) => { try { return await j

如何在不进行jwt令牌检查的情况下允许登录/注册查询

我在Apollo中获取用于登录/注册查询的jwt令牌时遇到问题。我试图理解如何不检查jwt令牌的正确性以进行查询(突变)登录/注册。例如,对于我的应用程序中的第一次登录,我没有令牌,因此空字符串或null或undefined不正确,我不能调用查询登录/注册

我尝试在上下文中检查令牌

const getTokenPayload = async (token?: string) => {
  try {
    return await jwt.verify(token, config.jwtSalt);
  } catch (e) {
    throw new ApolloError(`Token doesn't valid`, errorCodes.ERROR_TOKEN_IS_NOT_VALID);
  }
};

const apolloServerStart = (store) => {
  const server = new ApolloServer({
    context: async ({ req }) => {
      const tokenPayload = await getTokenPayload(req.headers.authorization);

      return {
        userId: tokenPayload.id,
      };
    },
    typeDefs,
    resolvers,
    dataSources: () => ({
      userAPI: new UserAPI({ store }),
      cardSetAPI: new CardSetAPI({ store }),
    }),
  });

  const app = express();
  server.applyMiddleware({ app });

  app.listen(
    { port: 4000 },
    () => console.log(`Server ready at http://localhost:4000${server.graphqlPath}`) // eslint-disable-line no-console
  );
};

connectToDb(apolloServerStart);

在实例化Apollo服务器时,如果JWT丢失,则在上下文生成函数中,您不能抛出任何错误

context: async ({ req }) => {
  let userId = null;
  try {
    const tokenPayload = await jwt.verify(req.headers.authorization, config.jwtSalt);
    userId = tokenPayload?.id;
  } catch (err) {}

  return {
    userId
  };
}
上面的代码将让每个请求传递给解析器,不管JWT是否无效/丢失。 因此,您必须保护您的私有解析程序(确保只有登录用户的请求到达它们)。为此,您可以定义一个所谓的“保护”。这是一个函数,它包装解析程序,检查上下文中是否存在userId,并在令牌无效(userId为null)时向客户端返回错误

用guard func包住所有的私有解析器。 不要用GUARD func包装登录和注册解析程序。这样,未经身份验证的用户可以调用它们