0

我已经配置了 API-Gateway 来调用 Cloud Function,我们还为这个 API-Gateway 主机配置了负载均衡器。但是当我们从我们的 Web 应用程序调用这个负载均衡器端点时,我们面临着 CORS 问题。

问题 1:请指导我如何在 API config open-api YAML 文件中添加 CORS 支持。问题 2:如何在这个 open-api 配置 YAML 文件中添加自定义身份验证端点?

高级流程:webapp --> 负载均衡器 url --> API-Gateway --> CloudFunction

我已根据 GCP 链接在云功能中添加了 CORS 后端支持:https ://cloud.google.com/functions/docs/writing/http#authentication_and_cors

云函数代码如下:

public class Demand implements HttpFunction {
private static final Logger logger = Logger.getLogger(Demand.class.getName());
// Use GSON (https://github.com/google/gson) to parse JSON content.
private static final Gson gson = new Gson();
@Override
public void service(HttpRequest request, HttpResponse response) throws Exception {
String contentType = request.getContentType().orElse("");
logger.info(() -> "contentType: " + contentType);
// Set CORS headers
// Allows GETs from any origin with the Content-Type
// header and caches preflight response for 3600s
response.appendHeader("Access-Control-Allow-Origin", "*");
System.out.println("Added preflight options request support::::::::::");
if ("OPTIONS".equals(request.getMethod())) {
System.out.println("OPTIONS::::::::::::::::");
response.appendHeader("Access-Control-Allow-Methods", "*");
response.appendHeader("Access-Control-Allow-Headers", "Content-Type");
response.appendHeader("Access-Control-Max-Age", "3600");
response.setStatusCode(HttpURLConnection.HTTP_NO_CONTENT);
return;
} 
// Handle the main request.
BufferedWriter writer = response.getWriter();
writer.write("CORS headers set successfully!");
} 

以下开放 API 规范:

--- 
info:
  description: Sample API on API Gateway with a Google Cloud Functions backend
  title: trigger-post
  version: 1.0.0
paths:
  /triggerondemand:
    post:
      consumes:
        - application/json
      operationId: triggerondemand
      parameters:
        - description: triggerondemand.
          in: body
          name: ondemand
          schema:
            properties:
              fileStatus: 
                type: string
              
            type: object
      responses:
        '201':
          description: Created
      summary: triggerondemand
      x-google-backend:
        address: >-
          https://us-east1-neodev-305805.cloudfunctions.net/demand
produces:
  - application/json
schemes:
  - https
swagger: '2.0'

浏览器报错如下:

Access to XMLHttpRequest at 'https://apitest.dev.app.com/triggerondemand' from origin 'https://dataplatform.dev.app.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

提前致谢

4

1 回答 1

0

您的两个问题的答案是,目前这是不可能的。

GCP API 网关目前不支持 CORS 的处理,虽然它在要实现的路线图中,但您可以使用解决方法来做到这一点,正如您在这个社区答案中看到的那样。

关于自定义身份验证,正如我在此处的回答中所描述的:

不幸的是,GCP API Gateway 没有为自定义身份验证提供此类选项,为了使用 API Gateway 进行身份验证,您必须使用文档中提供的备用身份验证方法之一。

于 2021-04-09T15:02:39.393 回答