首页 文章

从API网关自定义授权程序返回401缺少'Access-Control-Allow-Origin'标头

提问于
浏览
34

为了防止未登录的用户通过AWS API网关调用我的lambda函数,我正在使用Custom Authorizer lambda解决方案 .

如果请求被授权(200)并且我从被叫lambda得到响应,一切正常,我得到 Access-Control-Allow-Origin Headers .

但是如果请求未被授权,我会得到一个没有 Access-Control-Allow-Origin 标头的401,因此阻止我读取响应的401状态并将用户重定向到登录页面 .

我相信这是因为自定义自动化机制不知道请求需要使用CORS . 有谁知道这实际上是问题吗?你知道任何可能的解决方案吗?

5 回答

  • 14

    解决所有4XX错误(包括401错误)的最简单方法是转到“网关响应”,然后选择“默认4XX”,然后添加 Headers “Access-Control-Allow-Origin”,其值为'* ” .

    见截图:

  • 4

    是的,这是API Gateway自定义授权程序的已知错误 . 谢谢让我们注意到这个 . 我们部署修复程序后,团队将更新此帖子 . 不便之处敬请原谅 .

  • 2

    我很高兴地宣布新的网关响应功能,该功能允许您自定义不会调用您的集成的请求的错误响应 . 这允许您确保包含CORS头,即使在失败的身份验证请求中也是如此 .

    阅读我们的documentation中的更多内容,其中包括一个CORS示例 .

  • 12

    因为我花了一些时间来弄清楚如何将它们放在Cloud Formation中,所以这里有一个片段展示了如何设置它 .

    ...
        MyApi:
          Type: "AWS::ApiGateway::MyApi"
          Properties:
            Description: My API
            Name: "my-api"
        MyApiAuthorizer:
          Type: "AWS::ApiGateway::Authorizer"
          Properties:
             Name: "my-api-authorizer"
             IdentitySource: "method.request.header.Authorization"
             ProviderARNs:
               - !GetAtt MyUserPool.Arn
             RestApiId: !Ref MyAApi
             Type: COGNITO_USER_POOLS
        MyApiGatewayResponse:
          Type: "AWS::ApiGateway::GatewayResponse"
          Properties:
            ResponseParameters:
              "gatewayresponse.header.Access-Control-Allow-Origin": "'*'"
              "gatewayresponse.header.Access-Control-Allow-Headers": "'*'"
            ResponseType: UNAUTHORIZED
            RestApiId: !Ref MyApi
            StatusCode: "401"
    
  • 0

    添加上面的答案,如果你没有使用Cloudformation / SAM模板,你可以使用这个python脚本节省一些手动步骤:

    import boto3
    import sys
    
    if len(sys.argv) != 3:
        print("usage: python script.py <API_ID> <STAGE>")
        exit()
    
    client = boto3.client('apigateway')
    
    response = client.put_gateway_response(
        restApiId=sys.argv[1],
        responseType='UNAUTHORIZED',
        statusCode='401',
        responseParameters={
            "gatewayresponse.header.Access-Control-Allow-Origin": "'*'",
            "gatewayresponse.header.Access-Control-Allow-Headers": "'*'"
        }
    )
    response = client.create_deployment(
        restApiId=sys.argv[1],
        stageName=sys.argv[2])
    

相关问题