API GateWayにAPIKey認証とIP制限を実装してみました。

API GateWayにAPIKey認証とIP制限を実装してみました。

  SkyLightApi:
    Type: AWS::Serverless::Api
    Properties:
      Name: !Sub ${AWS::StackName}-api-gateway
      ApiKeySourceType: HEADER
      StageName: !Ref EnvName      
      Auth:
        ApiKeyRequired: true
        ResourcePolicy:
          CustomStatements: [
            {
              "Effect": "Allow",
              "Principal": "*",
              "Action": "execute-api:Invoke",
              "Resource": "execute-api:/*"
            },
            {
              "Effect": "Deny",
              "Principal": "*",
              "Action": "execute-api:Invoke",
              "Resource": "execute-api:/*",
              "Condition": {
                "NotIpAddress": {
                  "aws:SourceIp": !FindInMap [ Config, !Ref EnvName, allowIps ]
                }
              }
            }
          ]

  SkyLightUsagePlan:
    Type: AWS::ApiGateway::UsagePlan
    DependsOn:
      - SkyLightApi
      - SkyLightApiStage
    Properties:
      Description: Example usage plan to specify a monthly quota of 1000 requests and a rate of 100 requests per second.
      ApiStages:
        - ApiId: !Ref SkyLightApi
          Stage: !Sub '${EnvName}'
      UsagePlanName: "My Usage Plan"

  SkyLightApiKey:
    Type: AWS::ApiGateway::ApiKey
    DependsOn:
      - SkyLightApi
      - SkyLightApiStage
    Properties:
      Enabled: true
      Name: !Sub ${EnvName}-api-gateway-key
      StageKeys:
        - RestApiId: !Ref SkyLightApi
          StageName: !Ref EnvName

  SkyLightUsagePlanKey:
    Type: AWS::ApiGateway::UsagePlanKey
    DependsOn:
      - SkyLightApiKey
      - SkyLightUsagePlan
    Properties:
      KeyId: !Ref SkyLightApiKey
      KeyType: API_KEY
      UsagePlanId: !Ref SkyLightUsagePlan