Configure CORS for authorization errors (Api gateway HTTP + Lamda proxy + Cognito)

0

Hello, I'm using Api Gateway (HTTP Api) as a Lambda proxy using Cognito authorization. The domain off my app differs from the one of the api, which is why i need to provide CORS headers in the response.

I've already excluded OPTIONS calls from the authorization and provide the CORS headers from my lambda. That have solved my CORS issues.

But, if the Authentication fails, because of expired or invalid access_token, Api Gateway (i guess) will create an error response which doesn't have that headers included... At the moment the token expires, i'm simply getting CORS issues in the app which i can't handle probably.

I've already tried to do a parameter mapping but i can't save it (Operations on header access-control-allow-origin are restricted)

Is it possible to somehow add that headers into the response?

Thanks and regards

2回答
0

When API Gateway responds to an authentication or authorization error before passing the request to Lambda, it doesn't include the CORS headers. That makes the browser think it's a CORS error, even though it's actually an authentication/authorization error. To ensure CORS headers are included in the authentication error response from API Gateway, follow these steps:

  • Catch the Error in API Gateway
  • Customize Gateway Responses
    • In the Response Headers section, you can add the headers needed for CORS. For example, you might add:
    • Access-Control-Allow-Origin with the value set to '*' or your specific domain.
    • Access-Control-Allow-Credentials with the value true if needed.
    • Any other headers you'd typically add for CORS responses?
  • Response Mapping Templates
  • Re-deploy Your API
profile picture
エキスパート
回答済み 10ヶ月前
profile picture
エキスパート
レビュー済み 10ヶ月前
0

Thanks for the quick answer!

Unfortunately i can't find the settings to do that. For Lambda proxy integrations it seems that i can only do a parameter mapping. I've tried it already but can't save it: "Operations on header access-control-allow-origin are restricted"

In the meantime i have found a workaround which works for me:

  • Modified the cloud front distribution of my App and added a new origin and behavior.
  • It forwards everything from /api/* to my api gateway. Since the requests are being done from the same domain, i have no CORS issues anymore.
  • M2M requests are still directly targeting my api gateway since i don't need CORS headers in that case.

Thanks and regards

PatrykT
回答済み 10ヶ月前

ログインしていません。 ログイン 回答を投稿する。

優れた回答とは、質問に明確に答え、建設的なフィードバックを提供し、質問者の専門分野におけるスキルの向上を促すものです。

質問に答えるためのガイドライン

関連するコンテンツ