Подтвердить что ты не робот

API AWS SAM с авторизатором пулов пользователей Cognito

Как я могу создать API с AWS SAM, который делает авторизацию с использованием авторизованного администратора Cognito User Pools?

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

Я не понимаю, как мне связать их вместе?

4b9b3361

Ответ 1

Я не уверен, что вы можете указать авторизатор в SAM, но вы можете встроить Swagger в файлы SAM, которые могут это сделать. Это новая функция от 17 февраля [ ссылка ].

Я определенно не эксперт по Swagger или 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


Редактировать: Исправлен синтаксис Swagger 2.0 для раздела "безопасность", это должен быть список.

Ответ 2

Теперь вы можете ссылаться на неявно созданный шлюз API с помощью "ServerlessRestApi". Так что в свой шаблон SAM добавьте этот кусочек обычной Cloudformation, и все будет работать нормально

ApiCognitoAuthorizer:          
  Type: AWS::ApiGateway::Authorizer
  Properties:
    IdentitySource: 'method.request.header.Authorization'
    Name: ApiCognitoAuthorizer
    ProviderARNs:
      - 'arn:aws:cognito-idp:{region}:{userpoolIdentifier}'
    RestApiId: !Ref ServerlessRestApi
    Type: COGNITO_USER_POOLS

Ответ 3

Вы можете добавить свой Cognito User Authorizer непосредственно в SAM AWS::Serverless::Api.

  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      Cors: "'*'"
      Auth:
        DefaultAuthorizer: MyCognitoAuthorizer
        Authorizers:
          MyCognitoAuthorizer:
            UserPoolArn: 'arn:aws:cognito-.....' # YOUR COGNITO USER POOL ARN

и в вашем AWS::Serverless::Function вы можете добавить авторизатор функций, если вы не установили его по умолчанию. Или вы можете отключить его, используя Authorizer: 'NONE'.

Auth:
  Authorizer: MyCognitoAuthorizer

см. также документацию.

Ответ 4

Как упоминалось в @simones, следующее создаст авторизатор Cognito User Pool (шаблон CF).

ApiCognitoAuthorizer:          
 Type: AWS::ApiGateway::Authorizer
 Properties:
  IdentitySource: 'method.request.header.Authorization'
  Name: ApiCognitoAuthorizer
  ProviderARNs:
   - 'arn:aws:cognito-idp:{region}:{userpoolIdentifier}'
  RestApiId: !Ref ServerlessRestApi
  Type: COGNITO_USER_POOLS

Чтобы прикрепить его к методу ресурса, работает следующее (в файле Swagger):

 securityDefinitions:
  ApiCognitoAuthorizer:
    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:{region}:{userpoolIdentifier}

Затем добавьте к конкретным методам (в файле Swagger):

    security:
    - ApiCognitoAuthorizer: []

Ответ 5

Начиная с AWS SAM v1.8.0, вы можете сделать это, используя следующий синтаксис. Вы можете обратиться к этой статье для получения дополнительной информации.

Вкратце, определите Cognito Authorizer для вашего API с помощью API Authorizer Object. Затем установите Auth вашей лямбда-функции на ссылку на этот API.

MyApi:
  Type: AWS::Serverless::Api
  Properties:
    StageName: Prod
    Auth:
      DefaultAuthorizer: MyCognitoAuth # OPTIONAL
      Authorizers:
        MyCognitoAuth:
          # Can also accept an array
          UserPoolArn: !GetAtt MyCognitoUserPool.Arn 
          Identity: # OPTIONAL
            # OPTIONAL; Default: 'Authorization'
            Header: MyAuthorizationHeader 
            # OPTIONAL
            ValidationExpression: myAuthValidationExp
MyFunction:
  Type: AWS::Serverless::Function
  Properties:
    FunctionName: MyFunction
    ...
    Events:
      Post:
        Type: Api
        Properties:
          Path: /compute
          Method: POST
          RestApiId: !Ref MyApi
          Auth:
            Authorizer: MyCognitoAuth