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 個月前

您尚未登入。 登入 去張貼答案。

一個好的回答可以清楚地回答問題並提供建設性的意見回饋,同時有助於提問者的專業成長。

回答問題指南