AWS API Gateway с лямбда-авторизатором - PullRequest
0 голосов
/ 28 октября 2019

Я пытаюсь настроить API-шлюз, который принимает параметр прокси из пути запроса, а также параметр из Lambda-авторизатора, возвращает и помещает его в заголовок, чтобы его можно было передать моему запущенному API-интерфейсу REST Elastic BeanstalkВесенний ботинок.

Путь прокси работает должным образом;и я вижу, что моя лямбда-функция возвращает переменную "x-api-auth" в карте "context" согласно документации.

Единственная не работающая часть - это добавление «x-api-auth» в заголовок запроса. :( Всякий раз, когда я запускал свою сборку Jenkins для обновления стека Cloudformation, я получаю эту ошибку:

Errors found during import: Unable to put integration on 'ANY' for resource at path '/sfdc/v1/feature-api/{proxy+}': Invalid mapping expression specified: Validation Result: warnings : [], errors : [Invalid mapping expression specified: $context.authorizer.x-api-auth] (Service: AmazonApiGateway; Status Code: 400; Error Code: BadRequestException

Это очень расстраивает, и я дважды проверил документацию OpenAPI, чтобы убедиться, что мой синтаксис правильный. Любая помощьили советы будут наиболее ценными!

Вот шаблон Cloudformation, который я имею:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Data API pipeline initial Cloudformation template

Mappings:
  EnvironmentMapping:
    alpha:
      certificationArn: ""
      carfaxIpWhitelistRuleId: ""
      hostedZoneId: XYZ
      authLambda: ""
      sfdcAuthLambda: ""
      myApiNetworkLoadBalancer: ""
      sfdcAuthTimeout: 1
    beta:
      certificationArn: ""
      carfaxIpWhitelistRuleId: ""
      hostedZoneId: XYZ
      authLambda: ""
      sfdcAuthLambda: ""
      myApiNetworkLoadBalancer: ""
      sfdcAuthTimeout: 1
    prod:
      certificationArn: ""
      carfaxIpWhitelistRuleId: ""
      hostedZoneId: ABC
      authLambda: ""
      sfdcAuthLambda: ""
      myApiNetworkLoadBalancer: ""
      sfdcAuthTimeout: 1
Parameters:
  EnvironmentType:
    Type: "String"
    AllowedValues:
      - alpha
      - beta
      - prod

Conditions:
  UseProdCondition: !Equals [!Ref EnvironmentType, prod]

Resources:
  MyApiVpcLink:
    Type: AWS::ApiGateway::VpcLink
    Properties:
      Name: MyApiVpcLink
      Description: Allows data-api-gateway to access the VPC that my-api is on.
      TargetArns:
        - !FindInMap [EnvironmentMapping, !Ref EnvironmentType, myApiNetworkLoadBalancer]

  DataApi:
    DependsOn:
      - MyApiVpcLink
    Type: AWS::Serverless::Api
    Properties:
      Name: !Sub "${EnvironmentType}-data-api"
      StageName: !Ref EnvironmentType
      DefinitionBody:
        swagger: 2.0
        security:
          - ApiKey: []
        info:
          title: !Sub "${EnvironmentType}-data-api"
        paths:
          /sfdc/v1/my-api/{proxy+}:
            x-amazon-apigateway-any-method:
              produces:
                - application/json
              parameters:
                - in: path
                  name: proxy
                  required: true
                  schema:
                    type: string
                - in: header
                  name: x-api-auth
                  required: true
                  schema:
                    type: string
              security:
                - SfdcAuthorizer: []
                  ApiKey: []
              x-amazon-apigateway-api-key-source: HEADER
              x-amazon-apigateway-gateway-responses:
                ACCESS_DENIED:
                  statusCode: 403
                  responseTemplates:
                    application/json: '{\n\"message\": \"Access Denied\"}'
              x-amazon-apigateway-integration:
                httpMethod: ANY
                type: http_proxy
                connectionType: VPC_LINK
                connectionId: !Ref MyApiVpcLink
                passthroughBehavior: when_no_match
                uri: !If [UseProdCondition, 'http://myapp.production.aws-int.myorg.io/{proxy}',!Sub 'http://${EnvironmentType}-myapp.staging.aws-int.myorg.io/{proxy}']
                requestParameters:
                  integration.request.path.proxy: "method.request.path.proxy"
                  # -------------------- this breaks it once added -------------------
                  integration.request.header.x-api-auth: "$context.authorizer.x-api-auth"
                  # ------------------------------------------------------------------
        definitions:
          Empty:
            type: object
          Error:
            type: object
            properties:
              message:
                type: string
        securityDefinitions:
          SfdcAuthorizer:
            type: 'apiKey'
            name: 'Authorization'
            in: 'header'
            x-amazon-apigateway-authtype: 'custom'
            x-amazon-apigateway-authorizer:
              authorizerUri: !Join ['', [!Sub 'arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/', !FindInMap [EnvironmentMapping, !Ref EnvironmentType, sfdcAuthLambda], '/invocations']]
              authorizerResultTtlInSeconds: !FindInMap [EnvironmentMapping, !Ref EnvironmentType, sfdcAuthTimeout]
              type: 'token'
          ApiKey:
            type: apiKey
            name: x-api-key
            in: header

1 Ответ

0 голосов
/ 29 октября 2019

Что ж ... после того, как я начал изучать документацию, я стал жуликом и удалил "$" из "gration.request.header.x-api-auth "... И ЭТО РАБОТАЛО. Не уверен, что я чувствую по этому поводу.

Вот полный рабочий файл YAML. Я публикую его здесь на тот случай, если он должен помочь кому-то еще, кто пытается установить шлюз, который выбирает путь PROXY и ожидает возврата от Lambda-авторизатора.

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Data API pipeline initial Cloudformation template

Mappings:
  EnvironmentMapping:
    alpha:
      certificationArn: ""
      carfaxIpWhitelistRuleId: ""
      hostedZoneId: XYZ
      authLambda: ""
      sfdcAuthLambda: ""
      myApiNetworkLoadBalancer: ""
      sfdcAuthTimeout: 1
    beta:
      certificationArn: ""
      carfaxIpWhitelistRuleId: ""
      hostedZoneId: XYZ
      authLambda: ""
      sfdcAuthLambda: ""
      myApiNetworkLoadBalancer: ""
      sfdcAuthTimeout: 1
    prod:
      certificationArn: ""
      carfaxIpWhitelistRuleId: ""
      hostedZoneId: ABC
      authLambda: ""
      sfdcAuthLambda: ""
      myApiNetworkLoadBalancer: ""
      sfdcAuthTimeout: 1
Parameters:
  EnvironmentType:
    Type: "String"
    AllowedValues:
      - alpha
      - beta
      - prod

Conditions:
  UseProdCondition: !Equals [!Ref EnvironmentType, prod]

Resources:
  MyApiVpcLink:
    Type: AWS::ApiGateway::VpcLink
    Properties:
      Name: MYApiVpcLink
      Description: Allows data-api-gateway to access the VPC that feature-api is on.
      TargetArns:
        - !FindInMap [EnvironmentMapping, !Ref EnvironmentType, myApiNetworkLoadBalancer]

  DataApi:
    DependsOn:
      - MyApiVpcLink
    Type: AWS::Serverless::Api
    Properties:
      Name: !Sub "${EnvironmentType}-data-api"
      StageName: !Ref EnvironmentType
      DefinitionBody:
        swagger: 2.0
        security:
          - ApiKey: []
        info:
          title: !Sub "${EnvironmentType}-data-api"
        paths:
          /sfdc/v1/my-api/{proxy+}:
            x-amazon-apigateway-any-method:
              produces:
                - application/json
              parameters:
                - in: path
                  name: proxy
                  required: true
                  schema:
                    type: string
                - in: header
                  name: x-api-auth
                  required: true
                  schema:
                    type: string
              security:
                - SfdcAuthorizer: []
                  ApiKey: []
              x-amazon-apigateway-api-key-source: HEADER
              x-amazon-apigateway-gateway-responses:
                ACCESS_DENIED:
                  statusCode: 403
                  responseTemplates:
                    application/json: '{\n\"message\": \"Access Denied\"}'
              x-amazon-apigateway-integration:
                httpMethod: ANY
                type: http_proxy
                connectionType: VPC_LINK
                connectionId: !Ref MyApiVpcLink
                passthroughBehavior: when_no_match
                uri: !If [UseProdCondition, 'http://myapp.production.aws-int.myorg.io/{proxy}',!Sub 'http://${EnvironmentType}-myapp.staging.aws-int.myorg.io/{proxy}']
                requestParameters:
                  integration.request.path.proxy: "method.request.path.proxy"
                  integration.request.header.x-api-auth: "context.authorizer.x-api-auth"
        definitions:
          Empty:
            type: object
          Error:
            type: object
            properties:
              message:
                type: string
        securityDefinitions:
          SfdcAuthorizer:
            type: 'apiKey'
            name: 'Authorization'
            in: 'header'
            x-amazon-apigateway-authtype: 'custom'
            x-amazon-apigateway-authorizer:
              authorizerUri: !Join ['', [!Sub 'arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/', !FindInMap [EnvironmentMapping, !Ref EnvironmentType, sfdcAuthLambda], '/invocations']]
              authorizerResultTtlInSeconds: !FindInMap [EnvironmentMapping, !Ref EnvironmentType, sfdcAuthTimeout]
              type: 'token'
          ApiKey:
            type: apiKey
            name: x-api-key
            in: header
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...