Serverless Framework with AWS cognito generates CO

2019-03-01 09:30发布

问题:

I get this error message from the Angular frontend and I am not authorized to touch my lambda code:

`Access to fetch at 'https://testapicd.***.***.com/localization/v1/role' from origin 'https://localization.test.***.***.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.`

I have looked everywhere and there seems to be no bug in my code. My serverless code is

  getrole:
    handler: v1/handler_get_role.get_role
    name: get_role
    events:
      - http:
          path: v1/role
          method: get
          cors: true
          authorizer:
            name: CognitoCSAuthorizer
            type: COGNITO_USER_POOLS
            arn: ${file(config.${self:provider.stage}.json):userpoolarn}

I have triple-checked all the settings and everything seems correct. Any advice what to do? The functionality works in the dev environment but not when I deploy it to the test environment.

If I try the token directly against the API, then it does not work either (but worked fine in dev). I don't even believe anymore that it is a CORS problem. I think that the jwt token is wrong.

def get_role(event, context):
    return {
        'statusCode': 200,
        'headers': {
         'Content-Type': 'application/json',
         'Access-Control-Allow-Origin' : '*', # Required for CORS support to work
         'Access-Control-Allow-Credentials': 'true',
        },
        'body': json.dumps("TEST")
     }

回答1:

I have wrestled with this problem for hours (if not days) before and it turned out not only I had to enable cors on the serverless.yml file but also add the response headers as attributes in the object you return from your Lambda.

Something like this should do it:

const response = {
    statusCode: 200,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Credentials': true,
    },
    body: JSON.stringify({
      product: product
    }),
  };

This article saved my life back then and I hope it saves yours!



回答2:

The CORS error is thrown when you are making requests to servers in other domains. Depending on the server you are using to host the angular code there are many ways you can solve this.

You can try this google chrome extension to see if you can effectivelly fix the problem by ignoring the CORS errors.

One of the most commons ways to solve this problem is to configure a proxy server, but you can also solve it by whitelisting your test domain manipulating the header Access-Control-Allow-Origin in your requests.



回答3:

This line in serverless.yml

arn: ${file(config.${self:provider.stage}.json):userpoolarn}

Should have been

arn: ${file(config.${opt:stage}.json):userpoolarn}