0

I am using AWS CDK to run a RESTful API and I am getting the following preflight error when calling a POST endpoint:

Access to fetch at 'http://localhost:4000/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

I understand that the message says I should not be using a wildcard for the allow origin header but I don't believe I am. Here is my CDK config for the API:

const api = new RestApi(this, 'frontend-api', {
  restApiName: 'Frontend Service',
  description: 'This service serves the frontend.'
  defaultCorsPreflightOptions: {
    allowOrigins: [process.env.FRONTEND_URL],
    allowCredentials: true
  } 
});

const loginLambda = new NodejsFunction(this, 'loginFunction', {
  entry: 'dist/src/lambda/login.js',
  functionName: 'login',
});

const loginIntegration = new LambdaIntegration(loginLambda);
const loginResource = api.root.addResource('login');
loginResource.addMethod('POST', loginIntegration);

Here is the login lambda resoler

export const handler = async (event: any, context: any) => {
    return {
      statusCode: 200,
      body: JSON.stringify({
        success: true
      }),
      headers: {
        'Access-Control-Allow-Origin': [process.env.FRONTEND_URL],
        'Access-Control-Allow-Credentials': 'true',
        'Set-Cookie': serialize(
          'auth',
          'test',
          {
            httpOnly: true,
            expires: 'Sat, 21 Oct 2023 07:28:00 GMT'
          }
        )
      }
    };
}

As you can see I am not setting the origin to * so I am unsure why it's giving me the above error?

Just as a note I am running my lambda functions locally using sam local start-api - i'm not sure if this could be impacting the OPTIONS response?

red house 87
  • 1,837
  • 9
  • 50
  • 99
  • Have you added a route to handle the request method OPTIONS? – CBroe May 06 '22 at 10:25
  • No I havent, my understanding is that it is automatically managed by AWS. I have tried adding a mock integration as details here https://stackoverflow.com/questions/52752201/enabling-cors-for-aws-api-gateway-with-the-aws-cdk but it did not help – red house 87 May 06 '22 at 10:27
  • by the way, 'Access-Control-Allow-Origin' should be process.env.FRONTEND_URL instead of [process.env.FRONTEND_URL]. – lipeiran Oct 29 '22 at 22:40

0 Answers0