使用授权方后 AWS Amplify API 网关 cors 错误:aws_iam

AWS Amplify API Gateway cors error after using authorizer: aws_iam

我有 API 个执行 lambda 函数的网关端点。我想使用 aws_iam 作为授权方来保护我的 api 端点。我有一个为此设置了联合身份的用户池。但是,在将它实现到 cloudformation 模板中后,我从我的 angular 应用程序中使用经过身份验证的用户调用它时出现 cors 错误:

Access to XMLHttpRequest at 'api endpoint url' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

这是我的 cf 模板的代码:

create:
handler: functions/api-create.create
events:
  - http:
      path: get/create
      method: get
      authorizer: aws_iam
      cors: true

我的 lambda 函数如下所示:

export const create = async (event, context) => {


console.log('Create: ', event)
  console.log('Context: ', context)
  const response = {
    statusCode: 200,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Credentials': true,
    },
    body: JSON.stringify({
      product: "hallo"
    }),
  };

return response;
};

没有 authorizer: aws_iam 一切正常,我得到了预期的响应。有谁知道我在这里可能会遗漏什么。

我自己发现的。这是我所做的。

在为 GatewayResponsdefault 错误创建资源后,它们在我的 Serverless.yml 文件中也有正确的 headers 模板:

 Resources:
  GatewayResponseDefault4XX:
    Type: 'AWS::ApiGateway::GatewayResponse'
    Properties:
      ResponseParameters:
         gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
         gatewayresponse.header.Access-Control-Allow-Headers: "'*'"
      ResponseType: DEFAULT_4XX
      RestApiId:
        Ref: 'ApiGatewayRestApi'
  GatewayResponseDefault5XX:
    Type: 'AWS::ApiGateway::GatewayResponse'
    Properties:
      ResponseParameters:
         gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
         gatewayresponse.header.Access-Control-Allow-Headers: "'*'"
      ResponseType: DEFAULT_5XX
      RestApiId:
        Ref: 'ApiGatewayRestApi'

我收到的错误更改为 403 错误。现在我为我的 api 端点启用了云监视日志记录,因为我是通过授权用户调用端点的。

我现在看到了错误:

"message": "Credential should be scoped to a valid region, not 'us-east-1'. "

经过一些尝试和错误后,我发现我们的,因为我正在使用放大,所以我必须在区域中传递 api 放大配置,如下所示:

Amplify.configure({


Auth: {
    mandatorySignIn: true,
    region: awsExports.cognito.REGION,
    userPoolId: awsExports.cognito.USER_POOL_ID,
    identityPoolId: awsExports.cognito.IDENTITY_POOL_ID,
    userPoolWebClientId: awsExports.cognito.APP_CLIENT_ID,
  },
  API: {
    endpoints: [
        {
            name: awsExports.api.name,
            endpoint: awsExports.api.endpoint,
            region: "eu-west-1" // <-- This was missing
        }
    ]
}