当用户未经身份验证时,如何防止 Apollo 服务器解析器中执行代码?

问题描述 投票:0回答:1

我面临 Express Apollo 服务器的问题。我正在尝试创建一个包含一些解析器的 API,但并非所有解析器都需要身份验证。当用户通过身份验证时,一切正常。但是,如果用户未经过身份验证,我会遇到错误。

问题在于中间件已经发送了响应。但是,该函数还需要返回,导致出现以下错误:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

以下是相关代码片段:

const loginRequiredGql = (req, res, next) => {
  const nextWrapper = () => {};
  for (const middleware of auth.loginRequired) {
    middleware(req, res, nextWrapper);
  }
  // if the response is already sent then the useris not authenticated
  console.log(res.headersSent);
}

const resolvers = {
  Query: {
    hello: (root, args, { req, res }) => {
      return 'World';
    },

    auth_test: (root, args, { req, res }) => {
      loginRequiredGql(req, res);
      if (!res.headersSent) return "some code";

      // The problem is that this code will be executed even if the user is not logged in.
      // I want to stop the execution of the code if the user is not logged in.
      // I tried to use return, but it didn't work.
      console.log("============  ");
      // return ;
    },
  }
};

如果用户未登录,如何阻止代码执行? return 的使用似乎在这种情况下不起作用。任何建议或指导将不胜感激。

express authentication graphql apollo-server
1个回答
0
投票

我想我已经找到了解决方案。我的主要想法是直接从中间件发送响应。在我更新的方法中,我检查用户是否经过身份验证,如果没有,我会抛出错误以强制停止解析器。然后使用该错误发送响应


const loginReqGql = (req,res,next) => {
  const nextWrapper = () => {};
  auth.isAuthenticated(req,res,nextWrapper);
  if (!req.user) {
    const error = new Error('Not authenticated!');
    error.statusCode  = 401;
    throw error;
  }
}


const resolvers = {
  Query: {
    hello: (root, args, { req,res }) => {
      return 'World'},

    auth_test:  (root, args, { req,res }) => {
      loginReqGql(req,res);
      // my code
      return 'authenticated';
    
    },
  }

};

我现在想知道这种方法是否有意义以及是否有任何方法可以改进它。任何见解或建议都会有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.