使用GraphQL进行基本身份验证

时间:2017-07-24 19:57:15

标签: authentication graphql apollo-client

我在尝试查询使用基本身份验证的graphQL API时收到此错误: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

我创建networkInterface的代码是:

networkInterface = createNetworkInterface({
    uri: graphQlEndpoint.uri,
    opts: {
      credentials: graphQlEndpoint.credentials
    }
  });

  networkInterface.use([{
    applyMiddleware(req, next) {
      if (!req.options.header) {
        req.options.headers = {};
      }
      req.options.headers.authorization = 'Basic authorizationCode';
      next();
  }
}])

我猜这里的问题是,在我的网络应用程序进行查询之前,它会发送一个预检请求以及我收到错误401 的地方。我想知道这是否真的是我在那里得到错误的原因。

如果有,有办法解决吗?

在这种情况下,是否有其他身份验证比基本身份验证更好?

note :我正在使用 node.js 做出反应 apollo-client

感谢您提供任何帮助。

修改

// Enable Cross Origin Resource Sharing 
app.use('*', cors());

// Authorization: a user authentication is required
app.use((req, res, next) => {
  if (!getAuthUserName(req)) {
    logger('ERROR', 'Unauthorized: authenticated username is missing');
    res.status(401);
    res.send('Unauthorized: Access is denied due to missing credentials');
   }else {
    next();
   }
});

// Print Schema endpoint
app.use(rootUrl + '/schema', (req, res) => {
  res.set('Content-Type', 'text/plain');
  res.send(schemaPrinter.printSchema(schema));
});

// Print Introspection Schema endpoint
app.use(rootUrl + '/ischema', (req, res) => {
  res.set('Content-Type', 'text/plain');
  res.send(schemaPrinter.printIntrospectionSchema(schema));
});

// Stop node app
if (config.graphql.debugEnabled) {
  app.use(rootUrl + '/stop', (req, res) => {
    logger('INFO', 'Stop request');
    res.send('Stop request initiated');
    process.exit();
  });
}

// GraphQL endpoint
app.use(rootUrl, graphqlExpress(request => {
  const startTime = Date.now();

  request.uuid = uuidV1();
  request.workflow = {
    service: workflowService,
    context: getWorkflowContext(request)
  };
  request.loaders = createLoaders(config.loaders, request);
  request.resolverCount = 0;
  request.logTimeoutError = true;

  logger('INFO', 'new request ' + request.uuid + ' by ' + request.workflow.context.authUserName);

  request.incrementResolverCount =  function () {
    var runTime = Date.now() - startTime;
    if (runTime > config.graphql.queryTimeout) {
      if (request.logTimeoutError) {
        logger('ERROR', 'Request ' + request.uuid + ' query execution timeout');
      }
      request.logTimeoutError = false;
      throw('Query execution has timeout. Field resolution aborted');
    }
    this.resolverCount++;
  };

  return !config.graphql.debugEnabled ?
    {
      schema: schema,
      context: request,
      graphiql: config.graphql.graphiqlEnabled
    } :
    {
      schema: schema,
      context: request,
      graphiql: config.graphql.graphiqlEnabled,
      formatError: error => ({
        message: error.message,
        locations: error.locations,
        stack: error.stack
      }),
      extensions({ document, variables, operationName, result }) {
        return {
          requestId: request.uuid,
          runTime: Date.now() - startTime,
          resolverCount: request.resolverCount,
          operationCount: request.workflow.context.operationCount,
          operationErrorCount:     request.workflow.context.operationErrorCount
        };
      }
    };
}));

2 个答案:

答案 0 :(得分:0)

请尝试在graphql服务器端添加cors。我在这里发布了一些代码。

const corsOptions = {
    origin(origin, callback){
        callback(null, true);
    },
    credentials: true
};
graphQLServer.use(cors(corsOptions));
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type,Accept');
    next();
}
graphQLServer.use(allowCrossDomain);

我认为这可能对你有所帮助。

答案 1 :(得分:0)

您使用的graphql服务器正在拒绝由浏览器发出的预检请求,以查看该服务器是否将接受浏览器的请求。飞行前请求也称为OPTIONS请求。

服务器仅发送状态代码200。因此,除了您看到的CORS代码段之外,您还需要再添加一张支票。

这是可在快速应用程序中使用的cors中间件:

module.exports = (req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Methods",
    "OPTIONS, GET, POST, PUT, PATCH, DELETE"
  );
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
  //--------------OPTIONS-------------
  if (req.method === "OPTIONS") {
    return res.sendStatus(200);
  }
  next();
};