What is the Python code for AWS Cognito?

How to start using AWS cognito

Python code for AWS Cognito

You have a user pool and an identity pool. You also created the Web Hosted UI; so, you might be thinking how do I use it together?

If you like videos, visit the AWS Cognito Python tutorials by Paris Nakita Kejser. This is the only AWS Cognito in Python video tutorial. However, we will just pick two important flows from the above tutorial as some changes need to be made to the code mentioned in the video.

Sign-up using AWS Cognito, Python SDK Boto3

import os
import boto3
from dotenv import load_dotenv, find_dotenv

load_dotenv(find_dotenv())

# read the .env-sample, to load the environment variable.
dotenv_path = os.path.join(os.path.dirname(__file__), ".env-sample")
load_dotenv(dotenv_path)

username = "abc.xyz@gmail.com"
password = "#Abc1234"

client = boto3.client("cognito-idp", region_name="<region-name>")

print(os.getenv("COGNITO_USER_CLIENT_ID"))

# The below code, will do the sign-up
response = client.sign_up(
    ClientId=os.getenv("COGNITO_USER_CLIENT_ID"),
    Username=username,
    Password=password,
    UserAttributes=[{"Name": "email", "Value": username}],
)

There are certain prerequisites for this code to work.

In the current directory where you have the above code, create a file called .env-sample. In this file, you should have the macro COGNITO_USER_CLIENT_ID with the client ID from General Settings > App Client > App client id.

The above will be picked using the dotenv module.

When you execute the above code, you will get this back as a response:

{
   "UserConfirmed":false,
   "CodeDeliveryDetails":{
      "Destination":"a***@g***.com",
      "DeliveryMedium":"EMAIL",
      "AttributeName":"email"
   },
   "UserSub":"123456-d094-44e0-942d-789012134",
   "ResponseMetadata":{
      "RequestId":"123-1842-4027-345-789abc09234",
      "HTTPStatusCode":200,
      "HTTPHeaders":{
         "date":"Mon, 19 Apr 2021 05:11:44 GMT",
         "content-type":"application/x-amz-json-1.1",
         "content-length":"175",
         "connection":"keep-alive",
         "x-amzn-requestid":"123-1842-4027-345-789abc09234"
      },
      "RetryAttempts":0
   }
}

If you again go and check in General Setting > User and groups, the user should be confirmed.

Login and getting user details using AWS Cognito

You have now successfully created a new user and confirmed the user. The next logical step is to log in and get some user details from AWS Cognito.

You can achieve this by:

import os
import boto3
from dotenv import load_dotenv, find_dotenv

load_dotenv(find_dotenv())

dotenv_path = os.path.join(os.path.dirname(__file__), ".env-sample")
load_dotenv(dotenv_path)

username = "abc.xyz@gmail.com"
password = "#Abc1234"

client = boto3.client("cognito-idp", region_name="ap-south-1")

print(os.getenv("COGNITO_USER_CLIENT_ID"))

# Initiating the Authentication, 
response = client.initiate_auth(
    ClientId=os.getenv("COGNITO_USER_CLIENT_ID"),
    AuthFlow="USER_PASSWORD_AUTH",
    AuthParameters={"USERNAME": username, "PASSWORD": password},
)

# From the JSON response you are accessing the AccessToken
print(response)
# Getting the user details.
access_token = response["AuthenticationResult"]["AccessToken"]

response = client.get_user(AccessToken=access_token)
print(response)

Please note that you may sometimes get this error:

botocore.errorfactory.InvalidParameterException: An error occurred (InvalidParameterException) when calling the InitiateAuth operation: USER_PASSWORD_AUTH flow not enabled for this client

If you get this error, please check in General Settings > App Client > Auth Flow Configuration

You should have the ALLOW_USER_PASSWORD_AUTH selected. However, just for testing, enable all the options like this:

You will get a JSON as a response of initiate_auth, you have to just pick the AccessToken from it and pass it to get_user. Once that is done, you will get this as a response.

{
   "Username":"abc.xyz@gmail.com",
   "UserAttributes":[
      {
         "Name":"sub",
         "Value":"1234eb31-d094-44e0-942d-50a1234a66b"
      },
      {
         "Name":"email_verified",
         "Value":"true"
      },
      {
         "Name":"email",
         "Value":"abc.xyz@gmail.com"
      }
   ],
   "ResponseMetadata":{
      "RequestId":"xxxxxxx-1231-4f1c-b881-dcf10c54e576",
      "HTTPStatusCode":200,
      "HTTPHeaders":{
         "date":"Mon, 19 Apr 2021 08:26:10 GMT",
         "content-type":"application/x-amz-json-1.1",
         "content-length":"213",
         "connection":"keep-alive",
         "x-amzn-requestid":"xxxxxxx-1231-4f1c-b881-dcf10c54e576"
      },
      "RetryAttempts":0
   }
}

This is enough to understand how AWS Cognito works!

Learn more!

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved