如何使用CloudFormation中的Access和密钥保护AWS API网关?

时间:2018-05-10 22:33:23

标签: amazon-web-services aws-lambda amazon-cloudformation serverless aws-serverless

我使用AWS Toolkit for Visual Studio模板创建了无服务器的Lambda应用程序(我使用了Tutorial: Build and Test a Serverless Application with AWS Lambda)。我选择了“清空无服务器项目”并创建了与lambda function链接的简单API Gateway

CloudFormation模板如下所示:

{
  "AWSTemplateFormatVersion" : "2010-09-09",
  "Transform" : "AWS::Serverless-2016-10-31",
  "Description" : "An AWS Serverless Application.",

  "Resources" : {

    "Get" : {
      "Type" : "AWS::Serverless::Function",
      "Properties": {
        "Handler": "AWSServerless::AWSServerless.Functions::Get",
        "Runtime": "dotnetcore2.0",
        "CodeUri": "",
        "MemorySize": 256,
        "Timeout": 30,
        "Role": null,
        "Policies": [ "AWSLambdaBasicExecutionRole" ],
        "Events": {
          "PutResource": {
            "Type": "Api",
            "Properties": {
              "Path": "/",
              "Method": "GET"
            }
          }
        }
      }
    }
  },

  "Outputs" : {
    "ApiURL" : {
        "Description" : "API endpoint URL for Prod environment",
        "Value" : { "Fn::Sub" : "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/" }
    }
  }
}

现在我需要使用Access和Secret Keys保护我的API Gateway。我调查了一下,如果我是正确的,它应该看起来像下一个:

"security":[{"sigv4":[]}]

但是我还不清楚我应该在哪里申请它?可能我错了,可以用另一种方式完成。所以我的问题是:

如何在CloudFormation中使用Access和密钥保护API Gateway

1 个答案:

答案 0 :(得分:0)

您可以使用API keyAuthorizers

以下示例创建一个AWS Lambda函数的自定义授权程序。

"Authorizer": {
  "Type": "AWS::ApiGateway::Authorizer",
  "Properties": {
    "AuthorizerCredentials": { "Fn::GetAtt": ["LambdaInvocationRole", "Arn"] },
    "AuthorizerResultTtlInSeconds": "300",
    "AuthorizerUri" : {"Fn::Join" : ["", [
      "arn:aws:apigateway:",
      {"Ref" : "AWS::Region"},
      ":lambda:path/2015-03-31/functions/",
      {"Fn::GetAtt" : ["LambdaAuthorizer", "Arn"]}, "/invocations"
    ]]},
    "Type": "TOKEN",
    "IdentitySource": "method.request.header.Auth",
    "Name": "DefaultAuthorizer",
    "RestApiId": {
      "Ref": "RestApi"
    }
  }
}

(更新)
SO线程如何在模板中使用授权者

Reference an Authorizer definition in an API Gateway path