Cors problem when using custom authorizer

Hi,
I got problem with Cors and authorizer. I am using nestjs.

  • When authorize fail, cors worked fine.
  • But when authorizer success, cors not working.
  • When I remove authorizer: from serverless (No authorizer), the cors worked fine.

This is the error:

Access to XMLHttpRequest at 'https://dev.myservice.ai/users' from origin 'https://resttesttest.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

This is my serverless.yml.

functions:
  index:
    handler: src/lambda.handler
    memorySize: 192
    events:
    - http:
        path: '/{proxy+}'
        method: any
        # integration: lambda-proxy
        cors: true
        authorizer:
          arn: arn:aws:lambda:us-west-2:3333333333333:function:my-serverless-authentication-${opt:stage, self:provider.stage}-authorize
          resultTtlInSeconds: 0
          identitySource: method.request.header.Authorization
          identityValidationExpression: .*

resources:
  Resources:
    GatewayResponseDefault4XX:
      Type: 'AWS::ApiGateway::GatewayResponse'
      Properties:
        ResponseParameters:
          gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
          gatewayresponse.header.Access-Control-Allow-Headers: "'*'"
        ResponseType: DEFAULT_4XX
        RestApiId:
          Ref: 'ApiGatewayRestApi'

Any help!

1 Like

Okay I found the solution now.

Change cors: true to

    cors:
          origin: '*'
          headers:
            - Content-Type
            - X-Amz-Date
            - Authorization
            - X-Api-Key
            - X-Amz-Security-Token
            - X-Amz-User-Agent
          allowCredentials: true
3 Likes