【问题标题】:How to attach authorization/api key to the sam cli generated api?如何将授权/api 密钥附加到 sam cli 生成的 api?
【发布时间】:2020-08-21 13:41:35
【问题描述】:

我使用 sam cli 创建一个项目。当我打包并部署时,它默认创建 lambda 和带有 stage 和 prod 阶段、策略、角色等的 api 网关,而无需在 cloudformation 模板中明确定义(参见下面的代码)。当它自动生成 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

【问题讨论】:

标签: amazon-web-services aws-api-gateway aws-sam-cli


【解决方案1】:

我修改了您的代码以使用here 所示的 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 密钥存在:

【讨论】:

  • 谢谢。我更新了我的代码。我添加了三个资源,Api key、Usageplan 和 ApiUsagePlanKey,将它们联系在一起。添加这些后,我在创建 ApiUsagePlan 和 Apikey 时从 cloudformation 收到错误 - “指定的阶段标识符无效(服务 AmazonApiGateway:状态:404:错误代码:未找到异常......。我不确定如何引用艺名正确。
  • @ozil 我修好了。缺少两个 DependsOn,并且 apikey 太短。和之前一样,我修改了CodeUri: hello-world/,否则我无法运行部署。
  • @ozil 我对 swagger 不太熟悉,因此很难提供帮助。您可以考虑针对大摇大摆提出新的问题。这样其他人也可以尝试提供帮助。
  • @ozil 我认为应该是可能的。我在docs 中看到您可以在方法级别设置 api 密钥要求。不确定如何准确地修改现有答案,但我认为这对于一个新问题来说是个好问题。
  • 我将创建另一个问题
【解决方案2】:

您必须在您的 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

您可以阅读更多关于它的信息here

【讨论】:

  • 谢谢,我试过这个但我得到一个错误 -> api没有任何方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-10
  • 2020-08-17
  • 2018-03-20
  • 2021-10-01
相关资源
最近更新 更多