API网关选项方法抛出403

时间:2019-01-18 21:26:20

标签: amazon-web-services aws-lambda aws-api-gateway aws-sam

我有一个Custom Authorizer和一个API Gateway。通过SAM Module部署时,在启用Options Method时也会创建CORS。我真正不明白的是为什么自定义授权者会附加到Options端点? enter image description here

当我尝试从浏览器中调用端点时,这会抛出403,并且当我从Authorization方法中删除Options时,效果很好。

enter image description here

下面是template.yaml

AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'

Globals:
  Function:
    Runtime: nodejs8.10
  Api:
    Cors:
      AllowMethods: "'*'"
      AllowHeaders: "'*'"
      AllowOrigin: "'*'"

Resources:
  TestApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: dev
      Auth:
        DefaultAuthorizer: testAuthoriser
        Authorizers:
          testAuthoriser:
            FunctionArn:
              Fn::ImportValue: !Sub test-custom-autoriser
            Identity:
              Header: Authorization
              ValidationExpression: ^Bearer [-0-9a-zA-Z\._]*$
              ReauthorizeEvery: 30 

  Version:
    Type: 'AWS::Serverless::Function'
    Properties:
      FunctionName: test
      CodeUri: src/test
      Handler: index.test
      Events:
        EndPoint:
          Type: Api
          Properties:
            RestApiId: !Ref TestApi
            Path: /test
            Method: get
            Auth:
              Authorizer: testAuthoriser

我也启用了标题中的'Access-Control-Allow-Origin': '*'。不知道这是怎么回事。任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

这是答案,请参阅aws sam问题here

 Api:
    Cors:
      AllowHeaders: "'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization'" 
      AllowOrigin: "'*'"
    Auth:
      DefaultAuthorizer: CognitoAuthorizer
      Authorizers:
        CognitoAuthorizer:
          UserPoolArn: yourUserPool
      AddDefaultAuthorizerToCorsPreflight: False // <== this line

答案 1 :(得分:0)

对于CORS,AWS API Gateway将始终启用OPTIONS方法以允许进行飞行前测试。您可以在docs中阅读更多内容。

在浏览器中看到预检错误的原因,因为“ 403禁止”来自您的自定义授权者。 Custom Authorizer不会返回标题,因此如果Custom Authorzer拒绝了请求,您将始终看到预检错误。

要对此进行调试,请记录您的自定义授权者返回的策略。然后,您可以在CloudWatch中看到它。策略必须包含所请求资源的Allow语句。