1 year ago

#334320

test-img

Yasindu Thennakoon

CORS is blocked in the AWS HTTP API Gateway when a custom lambda authorizer is used

I have an API powered by HTTP API Gateway and Lambda that uses a custom authorizer. I use a custom authorizer for a few paths and other paths are haven't authorized and can be accessed publicly.

This setup works fine in postman, but when I use react app I got an error.

Access to XMLHttpRequest at 'https://********.execute-api.ap-southeast-1.amazonaws.com/api/public/v1/sign-in' from origin 'http://localhost:3000' 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 error also comes only for the authorized routes only. when I detach the authorizer for that routes it's working fine.

Here is my authorizer lambda

const handler = async (event) => {
  try {
    if (!event.headers.authorization) {
      log.info('Authorization header not found');
      return {
        'isAuthorized': false,
        "context": {}
      };
    }

    const tokenData = jwt.verify(event.headers.authorization, pem, { algorithms: ['RS256'] });
    console.log(tokenData);
    if (
      tokenData &&
      Object.keys(tokenData).length === 0 &&
      Object.getPrototypeOf(tokenData) === Object.prototype
    ) {
      log.info('Token object is empty. May be invalid token');
      return {
        'isAuthorized': false,
        "context": {}
      };
    }
    return {
      'isAuthorized': true,
      "context": {}
    };
  }
  catch (error) {
    log.error('verifyToken error', error);
    return {
      'isAuthorized': false,
      "context": {}
    };
  }
};

In the cors section, I didn't configure anything because I need to allow all the origins.

In my lambda function, I wrapped the express app and I use cors npm package for handling the cors as well.

enter image description here

enter image description here

How do I fix this CORS error? I'm not using the serverless.yml file. I do all the things through the AWS website. Anyone can explain how do I fix this using the AWS website.

amazon-web-services

aws-lambda

cors

aws-api-gateway

aws-http-api

0 Answers

Your Answer

Accepted video resources