API网关的AWS Cloudformation Link API密钥

时间:2018-08-07 23:17:17

标签: amazon-web-services aws-api-gateway amazon-cloudformation api-key

我有以下要通过SAM部署的Cloudformation模板。该模板可以正确创建DynamoDB表,API密钥,Lambda函数和API网关,但是我无法弄清楚需要在模板中指定哪些内容以将API KEY与API网关相关联。

我发现很多片段都显示了部分示例,但是我正在努力将它们拼凑在一起。

先谢谢您

丹尼

AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::Serverless-2016-10-31
Parameters:
  TableName:
    Type: String
    Default: 'influencetabletest'
    Description: (Required) The name of the new DynamoDB table Minimum 3   characters
    MinLength: 3
    MaxLength: 50
    AllowedPattern: ^[A-Za-z-]+$
    ConstraintDescription: 'Required parameter. Must be characters only. No numbers allowed.'
  CorsOrigin:
    Type: String
    Default: '*'
    Description: (Optional) Cross-origin resource sharing (CORS) Origin. You can specify a single origin, all "*" or leave empty and no CORS will be applied.
    MaxLength: 250
Conditions:
  IsCorsDefined: !Not [!Equals [!Ref CorsOrigin, '']]
Resources:
  ApiKey:
    Type: AWS::ApiGateway::ApiKey
    DependsOn:
      - ApiGetter
    Properties:
      Name: "TestApiKey"
      Description: "CloudFormation API Key V1"
      Enabled: "true"
  ApiGetter:
    Type: AWS::Serverless::Api
    Properties:
      StageName: prd
      DefinitionBody:
        swagger: 2.0
        info:
          title:
            Ref: AWS::StackName
        paths:
          /getdynamicprice:
            post:
              responses: {}
              x-amazon-apigateway-integration:
                httpMethod: POST
                type: aws_proxy
                uri:
                  Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LambdaGetter.Arn}/invocations
  LambdaGetter:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./index.js
      Handler: index.handler
      Runtime: nodejs8.10
      Environment:
        Variables:
          TABLE_NAME: !Ref TableName
          IS_CORS: IsCorsDefined
          CORS_ORIGIN: !Ref CorsOrigin
          PRIMARY_KEY: !Sub ${TableName}Id
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref TableName
      Events:
        Api:
          Type: Api
          Properties:
            Path: /getdynamicprice
            Method: POST
            RestApiId: !Ref ApiGetter
  DynamoDBTable:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: !Ref TableName
      AttributeDefinitions:
        -
          AttributeName: !Sub "${TableName}Id"
          AttributeType: "S"
      KeySchema:
        -
          AttributeName: !Sub "${TableName}Id"
          KeyType: "HASH"
      ProvisionedThroughput:
        ReadCapacityUnits: 1
        WriteCapacityUnits: 1
      StreamSpecification:
        StreamViewType: NEW_AND_OLD_IMAGES
Outputs:
  ApiKeyID:
    Value: !Ref ApiKey
  ApiUrl:
    Value: !Sub https://${ApiGetter}.execute-api.${AWS::Region}.amazonaws.com/prod/getdynamicprice
    Description: The URL of the API Gateway you invoke to get your dynamic pricing result.
  DynamoDBTableArn:
    Value: !GetAtt DynamoDBTable.Arn
    Description: The ARN of your DynamoDB Table
  DynamoDBTableStreamArn:
    Value: !GetAtt DynamoDBTable.StreamArn
    Description: The ARN of your DynamoDB Table Stream

2 个答案:

答案 0 :(得分:3)

这是一个示例模板,其中我已将我的API连接到API密钥。但这仅是可能的,因为我正在使用usage plans。我相信这是API密钥的主要目的。 API gateway usage plan

ApiKey: 
  Type: AWS::ApiGateway::ApiKey
  Properties: 
    Name: !Join ["", [{"Ref": "AWS::StackName"}, "-apikey"]]
    Description: "CloudFormation API Key V1"
    Enabled: true
    GenerateDistinctId: false
ApiUsagePlan:
  Type: "AWS::ApiGateway::UsagePlan"
  Properties:
    ApiStages: 
    - ApiId: !Ref <API resource name>
      Stage: !Ref <stage resource name>     
    Description: !Join [" ", [{"Ref": "AWS::StackName"}, "usage plan"]]
    Quota:
      Limit: 2000
      Period: MONTH
    Throttle:
      BurstLimit: 10
      RateLimit: 10
    UsagePlanName: !Join ["", [{"Ref": "AWS::StackName"}, "-usage-plan"]]
ApiUsagePlanKey:
  Type: "AWS::ApiGateway::UsagePlanKey"
  Properties:
    KeyId: !Ref <API key>
    KeyType: API_KEY
    UsagePlanId: !Ref ApiUsagePlan

如果没有使用计划,似乎没有办法做到这一点。

答案 1 :(得分:3)

我确实尝试了ASR的建议,但最终得到了一个更简单的方法。 AWS SAM(无服务器应用程序模型)包含预先打包的处理,不需要使用ApiGateway类型的资源。

要创建一个API网关,其阶段需要在标头中提供授权令牌,则以下简化的代码应为您做到这一点:

Resources:
  ApiGatewayEndpoint:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      Auth:
        ApiKeyRequired: true
        UsagePlan:
          CreateUsagePlan: PER_API
          UsagePlanName: GatewayAuthorization [any name you see fit]
  LambdaFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: lambda.handler
      Runtime: python3.7
      Timeout: 30
      CodeUri: .
      Events:
        PostEvent:
          Type: Api
          Properties:
            Path: /content
            Method: POST
            RequestParameters:
              - method.request.header.Authorization:
                  Required: true
                  Caching: true
            RestApiId:
              Ref: ApiGatewayEndpoint [The logical name of your gateway endpoint above]

元素:

Auth:
   ApiKeyRequired: true
   UsagePlan:
     CreateUsagePlan: PER_API

起到了什么作用。 Cloudformation为您处理管道,即。将自动创建并绑定Api密钥,UsagePlan和UsagePlanKey。

尽管这些文档绝对不是一流的,但它们确实提供了一些其他信息:https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-specification-resources-and-properties.html