API Gateway and Lambda Integration CORS issue

Hello,

I’m using AWS Cognito Federated Identities, and AWS API Gateway with LAMBDA integration:

submitUserVerification:
handler: handler.submitUserVerification
events:
  - http:
      method: POST
      path: verifications
      cors: true
      authorizer: AWS_IAM
      integration: lambda

When I use Postman to perform the request with AWS credentials it returns a successful response, as I want.

But with my Angular SPA is returning “localhost is not allowed by Access-Control-Allow-Origin” with the same credentials that a I used in Postman.

My lambda function:

module.exports.submitUserVerification = (event, context, callback) => {
  console.log(event)
  const created = moment().unix()
  const db = new AWS.DynamoDB()
  const params = {
    'Item': {
      'userId': {
        'S': event.identity.cognitoIdentityId
      },
      'created': {
        'N': created.toString()
      }
    },
    'TableName': 'verifications'
  }
  db.putItem(params, err => {
    if (err) {
      console.error(err)
      return callback(new Error(`[500] ${err.message}`))
    } else {
      return callback(null, mapVerificationItem(params.Item))
    }
  })
}

Any ideas what’s happening?

Setting CORS: true isn’t enough. That just enables OPTIONS in the API GW. You also need to return the Access-Control-Allow-Origin in the header response from your Lambda. You may also need to return Access-Control-Allow-Credentials and Access-Control-Expose-Headers too. Because you’re using Lambda integration you’ll need to add these to your template in the API GW.

2 Likes