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달 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인