Search code examples
reactjsamazon-web-servicescorsamazon-cognito

AWS Api Gateway Cors localhost


I have created an AWS HTTP API gateway. It maps to my lambda function. I have enabled JWT type authorization on my routes, it uses a cognito pool.

Calling the API from insomnia/postman with the auth token added works and returns as expected.

The CORS policy for the HTTP API is set in the following way:

x-amazon-apigateway-cors:
  allowMethods:
  - "DELETE"
  - "GET"
  - "HEAD"
  - "OPTIONS"
  - "PATCH"
  - "POST"
  - "PUT"
  allowHeaders:
  - "*"
  - "accept"
  - "access-control-allow-origin"
  - "authorization"
  - "content-type"
  exposeHeaders:
  - "*"
  - "accept"
  - "access-control-allow-origin"
  - "authorization"
  - "content-type"
  maxAge: 600
  allowCredentials: true
  allowOrigins:
  - "http://localhost:19006/"

I see the preflight OPTIONS request to my URL, and I also see that it gets 401 response for it, and doesn't return the set headers as above.

How can I enable cors while also having the cognito JWT type authorization?

Edit: I am sending the request from react side this way:

fetch('<URL>', { credentials: 'include', headers: { Authorization: 'Bearer ' + token,'content-type': 'text/html' }, redirect: 'follow', mode: 'cors' })

Solution

  • As far as I'm aware react doesn't send an authorisation header to the OPTIONS pre flight request. So if you've added authorisation to this path it will always respond with a 401. The OPTIONS resource should not have authorisation placed on it.