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 Answers
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
EXPERT
answered 9 months ago
profile picture
EXPERT
reviewed 9 months ago
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
answered 9 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions