인증 / API 키를 SAM CLI 생성 API에 연결하는 방법은 무엇입니까?

Aug 21 2020

프로젝트를 만들기 위해 sam cli를 사용했습니다. 이것을 패키징하고 배포하면 cloudformation 템플릿에 명시 적으로 정의 할 필요없이 기본적으로 단계 및 제품 단계, 정책, 역할 등이 포함 된 람다와 api 게이트웨이를 생성합니다 (아래 코드 참조). API 게이트웨이를 자동으로 생성하므로 아래 템플릿에서 생성 한 API에 대한 API 키 또는 일종의 인증을 추가하려면 어떻게 추가 / 첨부해야합니까?

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  simple-node-api
  Sample SAM Template for simple-node-api

Globals:
  Function:
    Timeout: 3

Resources:
 ServerlessHttpApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      Auth:
        ApiKeyRequired: true # sets for all methods
      DefinitionBody:
        swagger:2.0
        paths:
          "/myresource":
              post:
                 x-amazon-apigateway-integration
                    httpMethod: post
                    type: aws_proxy
                    uri: ...

 ApiKey: 
    Type: AWS::ApiGateway::ApiKey
    Properties: 
      Name: !Join ["", [{"Ref": "AWS::StackName"}, "-apikey"]]
      Description: "CloudFormation API Key V1"
      Enabled: true
      GenerateDistinctId: false
      Value: abcdefg123456
      StageKeys:
        - RestApiId: !Ref ServerlessHttpApi
          StageName: Prod

  ApiUsagePlan:
    Type: "AWS::ApiGateway::UsagePlan"
    Properties:
      ApiStages: 
        - ApiId: !Ref ServerlessHttpApi
          Stage: Prod
      Description: !Join [" ", [{"Ref": "AWS::StackName"}, "usage plan"]]
      Quota:
        Limit: 1000
        Period: MONTH
      UsagePlanName: !Join ["", [{"Ref": "AWS::StackName"}, "-usage-plan"]]

  ApiUsagePlanKey:
    Type: "AWS::ApiGateway::UsagePlanKey"
    DependsOn: 
      - ServerlessHttpApi
    Properties:
      KeyId: !Ref ApiKey
      KeyType: API_KEY
      UsagePlanId: !Ref ApiUsagePlan

  HelloWorldfunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello-world/
      Handler: app.lambdaHandler
      Runtime: python3.7
      Events:
        HelloWorld:
          Type: Api
          Properties:
            RestApiId: !Ref ServerlessHttpApi
            Path: /hello
            Method: get

Outputs:
  ServerlessHttpApi:
    Description: API Gateway endpoint URL for Prod stage for Hello World function
    Value:
      Fn::Sub: https://${ServerlessHttpApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
  HelloWorldfunction:
    Description: Express Backend Lambda Function ARN
    Value: !Sub HelloWorldfunction.Arn
  HelloWorldFunctionIamRole:
    Description: Implicit IAM Role created for Hello World function
    Value: !Sub HelloWorldFunctionRole.Arn

답변

2 Marcin Sep 03 2020 at 09:02

여기에 표시된대로 API 키를 사용하도록 코드를 수정 했습니다 .

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  simple-node-api
  Sample SAM Template for simple-node-api

Globals:
  Function:
    Timeout: 3

Resources:

  ServerlessHttpApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      Auth:
        ApiKeyRequired: true # sets for all methods

  ApiKey: 
    Type: AWS::ApiGateway::ApiKey
    DependsOn: [ApiUsagePlan]
    Properties: 
      Name: !Join ["", [{"Ref": "AWS::StackName"}, "-apikey"]]
      Description: "CloudFormation API Key V1"
      Enabled: true
      GenerateDistinctId: false
      Value: abcdefg123456665ffghsdghfgdhfgdh4565
      StageKeys:
        - RestApiId: !Ref ServerlessHttpApi
          StageName: Prod

  ApiUsagePlan:
    Type: "AWS::ApiGateway::UsagePlan"
    DependsOn:
      - ServerlessHttpApiProdStage
    Properties:
      ApiStages: 
        - ApiId: !Ref ServerlessHttpApi
          Stage: Prod
      Description: !Join [" ", [{"Ref": "AWS::StackName"}, "usage plan"]]
      Quota:
        Limit: 1000
        Period: MONTH
      UsagePlanName: !Join ["", [{"Ref": "AWS::StackName"}, "-usage-plan"]]

  ApiUsagePlanKey:
    Type: "AWS::ApiGateway::UsagePlanKey"
    DependsOn: 
      - ServerlessHttpApi
    Properties:
      KeyId: !Ref ApiKey
      KeyType: API_KEY
      UsagePlanId: !Ref ApiUsagePlan

  HelloWorldfunction:
    Type: AWS::Serverless::Function
    Properties:
      #CodeUri: hello-world/
      CodeUri: ./
      Handler: app.lambdaHandler
      Runtime: python3.7
      Events:
        HelloWorld:
          Type: Api
          Properties:
            RestApiId: !Ref ServerlessHttpApi
            Path: /hello
            Method: get

Outputs:
  ServerlessHttpApi:
    Description: API Gateway endpoint URL for Prod stage for Hello World function
    Value:
      Fn::Sub: https://${ServerlessHttpApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
  HelloWorldfunction:
    Description: Express Backend Lambda Function ARN
    Value: !Sub HelloWorldfunction.Arn
  HelloWorldFunctionIamRole:
    Description: Implicit IAM Role created for Hello World function
    Value: !Sub HelloWorldFunctionRole.Arn

코드를 실행할 수 있도록 몇 가지 부분을 주석 처리했으며, 배포되고 API 인증이 설정 되고 API 키 가 있는지 확인할 수 있습니다 .

1 CK__ Aug 21 2020 at 22:56

AWS SAM 템플릿 에서 언급해야합니다 . 다음은 예입니다.

Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      Auth:
        ApiKeyRequired: true # sets for all methods

  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: .
      Handler: index.handler
      Runtime: nodejs12.x
      Events:
        ApiKey:
          Type: Api
          Properties:
            RestApiId: !Ref MyApi
            Path: /
            Method: get
            Auth:
              ApiKeyRequired: true

여기에서 자세한 내용을 읽을 수 있습니다.