Package: pycognito
pyCognitoMakes working with AWS Cognito easier for Python developers.Getting StartedPython Versions SupportedInstallEnvironment VariablesCOGNITO_JWKS(optional)Cognito Utility Classpycognito.CognitoCognito MethodsRegisterAuthenticateAdmin AuthenticateInitiate Forgot PasswordConfirm Forgot PasswordChange PasswordConfirm Sign UpUpdate ProfileSend VerificationGet User ObjectGet UserGet UsersGet Group ObjectGet GroupGet GroupsCheck TokenVerify TokensLogoutAssociate Software TokenVerify Software TokenSet User MFA PreferenceRespond to Software Token MFA challengeRespond to SMS MFA challengeCognito SRP UtilityUsing AWSSRPDevice Authentication SupportReceiving DeviceKey and DeviceGroupKeyConfirming a DeviceUpdating Device StatusAuthenticating your DeviceForget DeviceSRP Requests AuthenticatorPython Versions Supported3.63.73.8Installpip install pycognitoEnvironment VariablesCOGNITO_JWKSOptional:This environment variable is a dictionary that represent the well known JWKs assigned to your user pool by AWS Cognito. You can find the keys for your user pool by substituting in your AWS region and pool id for the following example.https://cognito-idp.{aws-region}.amazonaws.com/{user-pool-id}/.well-known/jwks.jsonExample Value (Not Real):COGNITO_JWKS={"keys": [{"alg": "RS256","e": "AQAB","kid": "123456789ABCDEFGHIJKLMNOP","kty": "RSA","n": "123456789ABCDEFGHIJKLMNOP","use": "sig"},{"alg": "RS256","e": "AQAB","kid": "123456789ABCDEFGHIJKLMNOP","kty": "RSA","n": "123456789ABCDEFGHIJKLMNOP","use": "sig"}]}Cognito Utility ClassExample with All ArgumentsfrompycognitoimportCognitou=Cognito('your-user-pool-id','your-client-id',client_secret='optional-client-secret'username='optional-username',id_token='optional-id-token',refresh_token='optional-refresh-token',access_token='optional-access-token',access_key='optional-access-key',secret_key='optional-secret-key')Argumentsuser_pool_id:Cognito User Pool IDclient_id:Cognito User Pool Application client IDclient_secret:App client secret (if app client is configured with client secret)username:User Pool usernameid_token:ID Token returned by authenticationrefresh_token:Refresh Token returned by authenticationaccess_token:Access Token returned by authenticationaccess_key:AWS IAM access keysecret_key:AWS IAM secret keyExamples with Realistic ArgumentsUser Pool Id and Client ID OnlyUsed when you only need information about the user pool (ex. list users in the user pool)frompycognitoimportCognitou=Cognito('your-user-pool-id','your-client-id')UsernameUsed when the user has not logged in yet. Start with these arguments when you plan to authenticate with either SRP (authenticate) or admin_authenticate (admin_initiate_auth).frompycognitoimportCognitou=Cognito('your-user-pool-id','your-client-id',username='bob')TokensUsed after the user has already authenticated and you need to build a new Cognito instance (ex. for use in a view).frompycognitoimportCognitou=Cognito('your-user-pool-id','your-client-id',id_token='your-id-token',refresh_token='your-refresh-token',access_token='your-access-token')u.verify_tokens()# See method doc below; may throw an exceptionCognito AttributesAfter any authentication or other explicit verification of tokens, the following additional attributes will be available:id_claims— A dict of verified claims from the id tokenaccess_claims— A dict of verified claims from the access tokenCognito MethodsRegisterRegister a user to the user poolImportant:The arguments forset_base_attributesandadd_custom_attributesmethods depend on your user pool's configuration, and make sure the client id (app id) used has write permissions for the attributes you are trying to create. Example, if you want to create a user with a given_name equal to Johnson make sure the client_id you're using has permissions to edit or create given_name for a user in the pool.frompycognitoimportCognitou=Cognito('your-user-pool-id','your-client-id')u.set_base_attributes(email='you@you.com',some_random_attr='random value')u.register('username','password')Register with custom attributes.Firstly, add custom attributes on 'General settings -> Attributes' page.
Secondly, set permissions on 'Generals settings-> App clients-> Show details-> Set attribute read and write permissions' page.frompycognitoimportCognitou=Cognito('your-user-pool-id','your-client-id')u.set_base_attributes(email='you@you.com',some_random_attr='random value')u.add_custom_attributes(state='virginia',city='Centreville')u.register('username','password')Argumentsusername:User Pool usernamepassword:User Pool passwordattr_map:Attribute map to Cognito's attributesAuthenticateAuthenticates a userIf this method call succeeds the instance will have the following attributesid_token,refresh_token,access_token,expires_in,expires_datetime, andtoken_type.frompycognitoimportCognitou=Cognito('your-user-pool-id','your-client-id',username='bob')u.authenticate(password='bobs-password')Argumentspassword:- User's passwordAdmin AuthenticateAuthenticate the user using admin super privilegesfrompycognitoimportCognitou=Cognito('your-user-pool-id','your-client-id',username='bob')u.admin_authenticate(password='bobs-password')password:User's passwordInitiate Forgot PasswordSends a verification code to the user to use to change their password.u=Cognito('your-user-pool-id','your-client-id',username='bob')u.initiate_forgot_password()ArgumentsNo argumentsConfirm Forgot PasswordAllows a user to enter a code provided when they reset their password
to update their password.u=Cognito('your-user-pool-id','your-client-id',username='bob')u.confirm_forgot_password('your-confirmation-code','your-new-password')Argumentsconfirmation_code:The confirmation code sent by a user's request
to retrieve a forgotten passwordpassword:New passwordChange PasswordChanges the user's passwordfrompycognitoimportCognito#If you don't use your tokens then you will need to#use your username and password and call the authenticate methodu=Cognito('your-user-pool-id','your-client-id',id_token='id-token',refresh_token='refresh-token',access_token='access-token')u.change_password('previous-password','proposed-password')Argumentsprevious_password:- User's previous passwordproposed_password:- The password that the user wants to change to.Confirm Sign UpUse the confirmation code that is sent via email or text to confirm the user's accountfrompycognitoimportCognitou=Cognito('your-user-pool-id','your-client-id')u.confirm_sign_up('users-conf-code',username='bob')Argumentsconfirmation_code:Confirmation code sent via text or emailusername:User's usernameUpdate ProfileUpdate the user's profilefrompycognitoimportCognitou=Cognito('your-user-pool-id','your-client-id',id_token='id-token',refresh_token='refresh-token',access_token='access-token')u.update_profile({'given_name':'Edward','family_name':'Smith',},attr_map=dict())Argumentsattrs:Dictionary of attribute name, valuesattr_map:Dictionary map from Cognito attributes to attribute names we would like to show to our usersSend VerificationSend verification email or text for either the email or phone attributes.frompycognitoimportCognitou=Cognito('your-user-pool-id','your-client-id',id_token='id-token',refresh_token='refresh-token',access_token='access-token')u.send_verification(attribute='email')Argumentsattribute:- The attribute (email or phone) that needs to be verifiedGet User ObjectReturns an instance of the specified user_class.u=Cognito('your-user-pool-id','your-client-id',id_token='id-token',refresh_token='refresh-token',access_token='access-token')u.get_user_obj(username='bjones',attribute_list=[{'Name':'string','Value':'string'},],metadata={},attr_map={"given_name":"first_name","family_name":"last_name"})Argumentsusername:Username of the userattribute_list:List of tuples that represent the user's attributes as returned by the admin_get_user or get_user boto3 methodsmetadata: (optional)Metadata about the userattr_map: (optional)Dictionary that maps the Cognito attribute names to what we'd like to display to the usersGet UserGet all of the user's attributes. Gets the user's attributes using Boto3 and uses that info to create an instance of the user_classfrompycognitoimportCognitou=Cognito('your-user-pool-id','your-client-id',username='bob')user=u.get_user(attr_map={"given_name":"first_name","family_name":"last_name"})Argumentsattr_map:Dictionary map from Cognito attributes to attribute names we would like to show to our usersGet UsersGet a list of the user in the user pool.frompycognitoimportCognitou=Cognito('your-user-pool-id','your-client-id')user=u.get_users(attr_map={"given_name":"first_name","family_name":"last_name"})Argumentsattr_map:Dictionary map from Cognito attributes to attribute names we would like to show to our usersGet Group objectReturns an instance of the specified group_class.u=Cognito('your-user-pool-id','your-client-id')group_data={'GroupName':'user_group','Description':'description','Precedence':1}group_obj=u.get_group_obj(group_data)Argumentsgroup_data:Dictionary with group's attributes.Get GroupGet all of the group's attributes. Returns an instance of the group_class.
Requires developer credentials.frompycognitoimportCognitou=Cognito('your-user-pool-id','your-client-id')group=u.get_group(group_name='some_group_name')Argumentsgroup_name:Name of a groupGet GroupsGet a list of groups in the user pool. Requires developer credentials.frompycognitoimportCognitou=Cognito('your-user-pool-id','your-client-id')groups=u.get_groups()Check TokenChecks the exp attribute of the access_token and either refreshes the tokens by calling the renew_access_tokens method or does nothing.IMPORTANT:Access token is requiredu=Cognito('your-user-pool-id','your-client-id',id_token='id-token',refresh_token='refresh-token',access_token='access-token')u.check_token()ArgumentsNo arguments for check_tokenVerify TokensVerifies the currentid_tokenandaccess_token.
An exception will be thrown if they do not pass verification.
It can be useful to call this method immediately after instantiation when you're providing externally-remembered tokens to theCognito()constructor.
Note that if you're callingcheck_tokens()after instantitation, you'll still want to callverify_tokens()afterwards it in case it did nothing.
This method also ensures that theid_claimsandaccess_claimsattributes are set with the verified claims from each token.u=Cognito('your-user-pool-id','your-client-id',id_token='id-token',refresh_token='refresh-token',access_token='access-token')u.check_tokens()# Optional, if you want to maybe renew the tokensu.verify_tokens()ArgumentsNo arguments for verify_tokensLogoutLogs the user out of all clients and removes the expires_in, expires_datetime, id_token, refresh_token, access_token, and token_type attributes.frompycognitoimportCognito#If you don't use your tokens then you will need to#use your username and password and call the authenticate methodu=Cognito('your-user-pool-id','your-client-id',id_token='id-token',refresh_token='refresh-token',access_token='access-token')u.logout()ArgumentsNo arguments for logoutAssociate Software TokenGet the secret code to issue the software token MFA code.
Begins setup of time-based one-time password (TOTP) multi-factor authentication (MFA) for a user.frompycognitoimportCognito#If you don't use your tokens then you will need to#use your username and password and call the authenticate methodu=Cognito('your-user-pool-id','your-client-id',id_token='id-token',refresh_token='refresh-token',access_token='access-token')secret_code=u.associate_software_token()# Display the secret_code to the user and enter it into a TOTP generator (such as Google Authenticator) to have them generate a 6-digit code.ArgumentsNo arguments for associate_software_tokenVerify Software TokenVerify the 6-digit code issued based on the secret code issued by associate_software_token. If this validation is successful, Cognito will enable Software token MFA.frompycognitoimportCognito#If you don't use your tokens then you will need to#use your username and password and call the authenticate methodu=Cognito('your-user-pool-id','your-client-id',id_token='id-token',refresh_token='refresh-token',access_token='access-token')secret_code=u.associate_software_token()# Display the secret_code to the user and enter it into a TOTP generator (such as Google Authenticator) to have them generate a 6-digit code.code=input('Enter the 6-digit code.')device_name=input('Enter the device name')u.verify_software_token(code,device_name)Argumentscode:6-digit code generated by the TOTP generator appdevice_name:Name of a deviceSet User MFA PreferenceEnable and prioritize Software Token MFA and SMS MFA.
If both Software Token MFA and SMS MFA are invalid, the preference value will be ignored.frompycognitoimportCognito#If you don't use your tokens then you will need to#use your username and password and call the authenticate methodu=Cognito('your-user-pool-id','your-client-id',id_token='id-token',refresh_token='refresh-token',access_token='access-token')# SMS MFA are valid. SMS preference.u.set_user_mfa_preference(True,False,"SMS")# Software Token MFA are valid. Software token preference.u.set_user_mfa_preference(False,True,"SOFTWARE_TOKEN")# Both Software Token MFA and SMS MFA are valid. Software token preferenceu.set_user_mfa_preference(True,True,"SOFTWARE_TOKEN")# Both Software Token MFA and SMS MFA are disabled.u.set_user_mfa_preference(False,False)Argumentssms_mfa:SMS MFA enabled / disabled (bool)software_token_mfa:Software Token MFA enabled / disabled (bool)preferred:Which is the priority, SMS or Software Token? The expected value is "SMS" or "SOFTWARE_TOKEN". However, it is not needed only if both of the previous arguments are False.Respond to Software Token MFA challengeResponds when a Software Token MFA challenge is requested at login.frompycognitoimportCognitofrompycognito.exceptionsimportSoftwareTokenMFAChallengeException#If you don't use your tokens then you will need to#use your username and password and call the authenticate methodu=Cognito('your-user-pool-id','your-client-id',username='bob')try:u.authenticate(password='bobs-password')exceptSoftwareTokenMFAChallengeExceptionaserror:code=input('Enter the 6-digit code generated by the TOTP generator (such as Google Authenticator).')u.respond_to_software_token_mfa_challenge(code)When recreating a Cognito instancefrompycognitoimportCognitofrompycognito.exceptionsimportSoftwareTokenMFAChallengeException#If you don't use your tokens then you will need to#use your username and password and call the authenticate methodu=Cognito('your-user-pool-id','your-client-id',username='bob')try:u.authenticate(password='bobs-password')exceptSoftwareTokenMFAChallengeExceptionaserror:mfa_tokens=error.get_tokens()u=Cognito('your-user-pool-id','your-client-id',username='bob')code=input('Enter the 6-digit code generated by the TOTP generator (such as Google Authenticator).')u.respond_to_software_token_mfa_challenge(code,mfa_tokens)Argumentscode:6-digit code generated by the TOTP generator appmfa_tokens:mfa_token stored in MFAChallengeException. Not required if you have not regenerated the Cognito instance.Respond to SMS MFA challengeResponds when a SMS MFA challenge is requested at login.frompycognitoimportCognitofrompycognito.exceptionsimportSMSMFAChallengeException#If you don't use your tokens then you will need to#use your username and password and call the authenticate methodu=Cognito('your-user-pool-id','your-client-id',username='bob')try:u.authenticate(password='bobs-password')exceptSMSMFAChallengeExceptionaserror:code=input('Enter the 6-digit code you received by SMS.')u.respond_to_sms_mfa_challenge(code)When recreating a Cognito instancefrompycognitoimportCognitofrompycognito.exceptionsimportSMSMFAChallengeException#If you don't use your tokens then you will need to#use your username and password and call the authenticate methodu=Cognito('your-user-pool-id','your-client-id',username='bob')try:u.authenticate(password='bobs-password')exceptSMSMFAChallengeExceptionaserror:mfa_tokens=error.get_tokens()u=Cognito('your-user-pool-id','your-client-id',username='bob')code=input('Enter the 6-digit code generated by the TOTP generator (such as Google Authenticator).')u.respond_to_sms_mfa_challenge(code,mfa_tokens)Argumentscode:6-digit code you received by SMSmfa_tokens:mfa_token stored in MFAChallengeException. Not required if you have not regenerated the Cognito instance.Cognito SRP UtilityTheAWSSRPclass is used to performSRP(Secure Remote Password protocol)authentication.
This is the preferred method of user authentication with AWS Cognito.
The process involves a series of authentication challenges and responses, which if successful,
results in a final response that contains ID, access and refresh tokens.Using AWSSRPTheAWSSRPclass takes a username, password, cognito user pool id, cognito app id, an optional
client secret (if app client is configured with client secret), an optional pool_region orboto3client.
Afterwards, theauthenticate_userclass method is used for SRP authentication.importboto3frompycognito.aws_srpimportAWSSRPclient=boto3.client('cognito-idp')aws=AWSSRP(username='username',password='password',pool_id='user_pool_id',client_id='client_id',client=client)tokens=aws.authenticate_user()Device Authentication SupportYou must use theUSER_SRP_AUTHauthentication flow to use the device tracking feature. Read more aboutRemembered DevicesReceiving DeviceKey and DeviceGroupKeyOnce theauthenticate_userclass method is used for SRP authentication, the response also returnsDeviceKeyandDeviceGrouKey.
These Keys will later be used to confirm the device.importboto3frompycognito.aws_srpimportAWSSRPclient=boto3.client('cognito-idp')aws=AWSSRP(username='username',password='password',pool_id='user_pool_id',client_id='client_id',client=client)tokens=aws.authenticate_user()device_key=tokens["AuthenticationResult"]["NewDeviceMetadata"]["DeviceKey"]device_group_key=tokens["AuthenticationResult"]["NewDeviceMetadata"]["DeviceGroupKey"]Confirming a DeviceTheconfirm_deviceclass method is used for confirming a device, it takes two inputs,tokensandDeviceName(DeviceNameis optional).
The method returns two values,responseanddevice_password.device_passwordwill later be used to authenticate your device with
the Cognito user pool.response,device_password=user.confirm_device(tokens=tokens)Updating Device StatusTheupdate_device_statusclass method is used to update whether or not your device should be remembered. This method takes
three inputs,is_remembered,access_tokenanddevice_key.is_rememberedis a boolean value, which sets the device status as"remembered"onTrueand"not_remembered"onFalse,access_tokenis the Access Token provided by Cognito anddevice_keyis the key
provided by theauthenticate_usermethod.response=user.update_device_status(False,tokens["AuthenticationResult"]["AccessToken"],device_key)Authenticating your DeviceTo authenticate your Device, you can just adddevice_key,device_group_keyanddevice_passwordto the AWSSRP class.importboto3frompycognito.aws_srpimportAWSSRPclient=boto3.client('cognito-idp')aws=AWSSRP(username='username',password='password',pool_id='user_pool_id',client_id='client_id',client=client,device_key="device_key",device_group_key="device_group_key",device_password="device_password")tokens=aws.authenticate_user()Forget DeviceTo forget device, you can call theforget_deviceclass method. It takesaccess_tokenanddevice_keyas input.resonse=aws.forget_device(access_token='access_token',device_key='device_key')SRP Requests Authenticatorpycognito.utils.RequestsSrpAuthis aRequestsauthentication plugin to automatically populate an HTTP header with a Cognito token. By default, it'll populate
theAuthorizationheader using the Cognito Access Token as abearertoken.RequestsSrpAuthhandles fetching new tokens using the refresh tokens.Usageimportrequestsfrompycognito.utilsimportRequestsSrpAuthauth=RequestsSrpAuth(username='myusername',password='secret',user_pool_id='eu-west-1_1234567',client_id='4dn6jbcbhqcofxyczo3ms9z4cc',user_pool_region='eu-west-1',)response=requests.get('http://test.com',auth=auth)