AWS Cognito Python Sample Code

Python 2017.01.11 11:09 Posted by 김한별 behonestar

AWS Cognito를 통해 임시 AWS credentials를 발급받는 Python 예제 코드입니다.

ADMIN_NO_SRP_AUTH 방식을 사용하기 때문에 AWS credentials가 제공된 환경에서 동작합니다. 


Pre-Requirements

  • AWS Cognito의 User Pool과 Identity Pool이 생성되어 있어야합니다.
  • User Pool App을 생성할 때 Generate client secret 옵션이 비활성화되어야 합니다.
  • User Pool App의 ADMIN_NO_SRP_AUTH 옵션이 활성화되어야 합니다.

Auth Flow



# -*- coding: utf-8 -*-

import boto3


class Cognito():

    region = 'ap-northeast-2'

    user_pool_id = 'ap-northeast-2_xxxxxxxxx'

    app_client_id = 'hjohd8ijicoxxxxxxxxxxxxxx'

    identity_pool_id = 'ap-northeast-2:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'

    account_id = 'xxxxxxxxxxxx'


    def sign_up(self, username, password, email):

        idp_client = boto3.client('cognito-idp')

        resp = idp_client.sign_up(ClientId=self.app_client_id,

                                  Username=username,

                                  Password=password,

                                  UserAttributes=[{'Name': 'email', 'Value': email}])

        return resp


    def confirm_sign_up(self, username, confirm_code):

        idp_client = boto3.client('cognito-idp')

        resp = idp_client.confirm_sign_up(ClientId=self.app_client_id,

                                          Username=username,

                                          ConfirmationCode=confirm_code)

        return resp


    def sign_in_admin(self, username, password):

        # Get ID Token

        idp_client = boto3.client('cognito-idp')

        resp = idp_client.admin_initiate_auth(UserPoolId=self.user_pool_id,

                                              ClientId=self.app_client_id,

                                              AuthFlow='ADMIN_NO_SRP_AUTH',

                                              AuthParameters={'USERNAME': username,'PASSWORD': password})

        

        provider = 'cognito-idp.%s.amazonaws.com/%s' % (self.region, self.user_pool_id)

        token = resp['AuthenticationResult']['IdToken']


        # Get IdentityId

        ci_client = boto3.client('cognito-identity')

        resp = ci_client.get_id(AccountId=self.account_id,

                               IdentityPoolId=self.identity_pool_id,

                               Logins={provider:token})

        

        # Get Credentials

        resp = ci_client.get_credentials_for_identity(IdentityId=resp['IdentityId'],

                                                      Logins={provider: token})

        return resp