8

如何創建使用Cognito User Pools授權人進行授權的AWS SAM API?具有Cognito User Pools授權人的AWS SAM API

Theres AWS::ApiGateway::Authorizer。但是......

{ 
    "Type" : "AWS::ApiGateway::Authorizer", 
    "Properties" : { 
    "AuthorizerCredentials" : String, 
    "AuthorizerResultTtlInSeconds" : Integer, 
    "AuthorizerUri" : String, 
    "IdentitySource" : String, 
    "IdentityValidationExpression" : String, 
    "Name" : String, 
    "ProviderARNs" : [ String, ... ], 
    "RestApiId" : String, 
    "Type" : String 
    } 
} 

它看起來像RestApiId是指使用該授權的API?但隨着AWS SAM,我的API定義像

Resources: 
    Ec2Index: 
    Type: AWS::Serverless::Function 
    Properties: 
     Handler: ec2/index.handler 
     Runtime: nodejs6.10 
     CodeUri: ./src 
     FunctionName: 'ApiEc2IndexHandler' 
     Description: 'List EC2 resources' 
     Timeout: 30 
     Role: 'arn:aws:iam::598545985414:role/awsmanagement-lambda-management' 
     Events: 
     Ec2Index: 
      Type: Api 
      Properties: 
      Path: /ec2 
      Method: get 

我不明白我怎麼他們聯想到一起?

回答

2

我不確定你可以在SAM中指定一個授權者,但是你可以在可以執行此操作的SAM文件中嵌入Swagger。這是截至2月17日的新功能[ref]。

我絕對不是揚鞭或SAM專家,但它看起來像你想是這樣的:

AWSTemplateFormatVersion: '2010-09-09' 
Transform: AWS::Serverless-2016-10-31 
Description: Simple API Endpoint configured using Swagger specified inline and backed by a Lambda function 
Resources: 
    Ec2Index: 
    Type: AWS::Serverless::Api 
    Properties: 
     StageName: <stage> 
     DefinitionBody: 
      swagger: 2.0 
      info: 
       title: 
       Ref: AWS::StackName 
      securityDefinitions: 
       cognitoUserPool: 
       type: apiKey, 
       name: "Authorization" 
       in: header 
       x-amazon-apigateway-authtype: cognito_user_pools 
       x-amazon-apigateway-authorizer: 
        type: cognito_user_pools 
        providerARNs: 
        - arn:aws:cognito-idp:${AWS::Region}:{AWS::AccountId}:userpool/<user_pool_id> 
      paths: 
       "/ec2": 
       get: 
        security: 
        cognitoUserPool: [] 
        x-amazon-apigateway-integration: 
        httpMethod: POST 
        type: aws_proxy 
        uri: 
         Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${Ec2IndexLamb.Arn}/invocations 
        responses: {} 
      swagger: '2.0' 
    Ec2IndexLamb: 
    Type: AWS::Serverless::Function 
    Properties: 
     Handler: ec2/index.handler 
     Runtime: nodejs6.10 
     CodeUri: ./src 
     FunctionName: 'ApiEc2IndexHandler' 
     Description: 'List EC2 resources' 
     Timeout: 30 
     Role: 'arn:aws:iam::598545985414:role/awsmanagement-lambda-management' 
     Events: 
     Ec2Index: 
      Type: Api 
      Properties: 
      Path: /ec2 
      Method: get 

參考文獻:

https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html#apigateway-enable-cognito-user-pool

https://github.com/awslabs/serverless-application-model/blob/master/examples/2016-10-31/inline_swagger/template.yaml