簡體   English   中英

AWS Api 網關和 Cognito 導致 CORS 錯誤

[英]AWS Api Gateway and Cognito cause CORS errors

我不知道如何開始,在將 API 網關與 Cognito 作為授權方一起使用時,我遇到了 CORS 錯誤。 我在這上面花了很多時間,我相信我已經閱讀了整個 inte.net 以弄清楚發生了什么和錯了什么。 那么讓我們從一個簡單的例子開始。 我的 lambda:

import json
def handler(event, context):
    print('Lambda is here')
    return dict(
        statusCode=200,
        headers={
            'Access-Control-Allow-Headers': '*',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': '*',
            'Access-Control-Allow-Credentials': 'true',
        },
        body=json.dumps({'message': 'lambda works'})
    )

HTML測試CORS和授權的代碼:

<head>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<script>
        axios.get(
            "api_gateway_url",
        )
        .then(response =>alert(response.data.message))
        .catch(error => {
            console.log(error)
            alert("ERROR")
        })
</script>
</body>

對於API網關不認證,響應為:
在此處輸入圖像描述

對於API認證網關,響應為:
在此處輸入圖像描述 在此處輸入圖像描述

響應代碼取決於 API 網關的配置。 我已經改變了很多次我能改變的一切,我正在通過設置測試它的設置,但沒有任何幫助。 我在啟用 CORS 配置下的方法響應、集成響應和網關響應等位置添加了 CORS 標頭。 根據配置,我有一些狀態代碼 401、403 和 500,並且總是出現 CORS 錯誤。
雖然測試請求沒有觸及 lambda,因此上述錯誤不是 lambda 執行的結果。

我已經通過使用 CDK 部署它來測試它,我創建了一個示例代碼,您也可以在本地環境中嘗試。 代碼鏈接https://gitlab.com/magnus250/cognito-api-gateway-cdk-problems/

好的,我終於解決了我的問題。 @sampath-dilhan @chris-smith 謝謝。 那么讓我描述一下我是如何實現它的。

我認為整個 API 網關都被竊聽了,你永遠不知道你到底配置了什么。 API 網關的基礎開發由 CDK 提供,然后我嘗試不同的配置以從控制台啟用 CORS。 我閱讀了有關 CORS 配置的整個 inte.net,並嘗試使用這些知識啟用 CORS,總是重新部署 API 並等待一段時間直到測試。

下面我放了適合我的 CDK 配置。 對於遇到問題的人,我建議始終銷毀您的堆棧並在干凈的環境中重新部署它,因為正如我已經提到的,我相信 API 網關存在漏洞。 該代碼還具有域和證書定義。

    def create_api_gateway(
        self,
        prefix: str,
        domain: str,
        certificate_arn: str,
        cognito_user_pool_arn: str,
        handler: _lambda.Function,
    ) -> None:
        base_api = apigateway.RestApi(
            self,
            f"{prefix}-authorized-rest-api",
            deploy_options=apigateway.StageOptions(
                throttling_burst_limit=100,
                throttling_rate_limit=100,
                caching_enabled=False,
                cache_cluster_enabled=False,
            ),
            default_cors_preflight_options=apigateway.CorsOptions(
                allow_headers=[
                    "Content-Type",
                    "X-Amz-Date",
                    "Authorization",
                    "X-Api-Key",
                ],
                allow_methods=["*"],
                allow_credentials=True,
                allow_origins=["*"],
            ),
            domain_name=apigateway.DomainNameOptions(
                certificate=certificatemanager.Certificate.from_certificate_arn(
                    self,
                    f"{prefix}-certificate",
                    certificate_arn=certificate_arn,
                ),
                domain_name=f"api.{domain}",
                endpoint_type=apigateway.EndpointType.EDGE,
            ),
        )
        response_types = [
            apigateway.ResponseType.DEFAULT_4_XX,
            apigateway.ResponseType.DEFAULT_5_XX,
        ]
        for response_type in response_types:
            base_api.add_gateway_response(
                f"{prefix}-api-gateway-{response_type.response_type}",
                type=response_type,
                response_headers={
                    "Access-Control-Allow-Origin": "'*'",
                    "Access-Control-Allow-Headers": "'*'",
                    "Access-Control-Allow-Methods": "'*'",
                    "Access-Control-Allow-Credentials": "'true'",
                },
            )

        user_pool = cognito.UserPool.from_user_pool_arn(
            self, f"{prefix}-user-pool", user_pool_arn=cognito_user_pool_arn
        )
        authorizer = apigateway.CognitoUserPoolsAuthorizer(
            self,
            f"{prefix}-authorizer",
            authorizer_name=f"{prefix}-authorizer",
            cognito_user_pools=[user_pool],
        )

        get_widgets_integration = apigateway.LambdaIntegration(handler)
        resource = base_api.root.add_resource("{proxy+}")
        resource.add_method(
            "ANY",
            get_widgets_integration,
            authorizer=authorizer,
        )

        cdk.CfnOutput(self, f"{prefix}-api-url", value=base_api.url)

        zone = route53.HostedZone.from_lookup(self, f"{prefix}-hosted-zone", domain_name=domain)
        route53.ARecord(
            self,
            f"{prefix}-dns-record",
            record_name="api",
            zone=zone,
            target=route53.RecordTarget.from_alias(route53_targets.ApiGateway(base_api)),
        )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM