pycognito


Namepycognito JSON
Version 2023.5.0 PyPI version JSON
download
home_pagehttps://github.com/pvizeli/pycognito
SummaryPython class to integrate Boto3's Cognito client so it is easy to login users. With SRP support.
upload_time2023-05-26 13:41:58
maintainer
docs_urlNone
authorPascal Vizeli
requires_python
licenseApache License 2.0
keywords aws cognito api gateway serverless
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # pyCognito

Makes working with AWS Cognito easier for Python developers.

## Getting Started

- [Python Versions Supported](#python-versions-supported)
- [Install](#install)
- [Environment Variables](#environment-variables)
  - [COGNITO_JWKS](#cognito-jwks) (optional)
- [Cognito Utility Class](#cognito-utility-class) `pycognito.Cognito`
  - [Cognito Methods](#cognito-methods)
    - [Register](#register)
    - [Authenticate](#authenticate)
    - [Admin Authenticate](#admin-authenticate)
    - [Initiate Forgot Password](#initiate-forgot-password)
    - [Confirm Forgot Password](#confirm-forgot-password)
    - [Change Password](#change-password)
    - [Confirm Sign Up](#confirm-sign-up)
    - [Update Profile](#update-profile)
    - [Send Verification](#send-verification)
    - [Get User Object](#get-user-object)
    - [Get User](#get-user)
    - [Get Users](#get-users)
    - [Get Group Object](#get-group-object)
    - [Get Group](#get-group)
    - [Get Groups](#get-groups)
    - [Check Token](#check-token)
    - [Verify Tokens](#verify-tokens)
    - [Logout](#logout)
    - [Associate Software Token](#associate-software-token)
    - [Verify Software Token](#verify-software-token)
    - [Set User MFA Preference](#set-user-mfa-preference)
    - [Respond to Software Token MFA challenge](#respond-to-software-token-mfa-challenge)
    - [Respond to SMS MFA challenge](#respond-to-sms-mfa-challenge)
- [Cognito SRP Utility](#cognito-srp-utility)
  - [Using AWSSRP](#using-awssrp)
- [SRP Requests Authenticator](#srp-requests-authenticator)

## Python Versions Supported

- 3.6
- 3.7
- 3.8

## Install

`pip install pycognito`

## Environment Variables

#### COGNITO_JWKS

**Optional:** 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.json`

**Example Value (Not Real):**

```commandline
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 Class

### Example with All Arguments

```python
from pycognito import Cognito

u = 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')
```

#### Arguments

- **user_pool_id:** Cognito User Pool ID
- **client_id:** Cognito User Pool Application client ID
- **client_secret:** App client secret (if app client is configured with client secret)
- **username:** User Pool username
- **id_token:** ID Token returned by authentication
- **refresh_token:** Refresh Token returned by authentication
- **access_token:** Access Token returned by authentication
- **access_key:** AWS IAM access key
- **secret_key:** AWS IAM secret key

### Examples with Realistic Arguments

#### User Pool Id and Client ID Only

Used when you only need information about the user pool (ex. list users in the user pool)

```python
from pycognito import Cognito

u = Cognito('your-user-pool-id','your-client-id')
```

#### Username

Used 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).

```python
from pycognito import Cognito

u = Cognito('your-user-pool-id','your-client-id',
    username='bob')
```

#### Tokens

Used after the user has already authenticated and you need to build a new Cognito instance (ex. for use in a view).

```python
from pycognito import Cognito

u = 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 exception
```

## Cognito Attributes

After 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 token
- `access_claims` — A dict of verified claims from the access token

## Cognito Methods

#### Register

Register a user to the user pool

**Important:** The arguments for `set_base_attributes` and `add_custom_attributes` methods 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.

```python
from pycognito import Cognito

u = 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.

```python
from pycognito import Cognito

u = 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')
```

##### Arguments

- **username:** User Pool username
- **password:** User Pool password
- **attr_map:** Attribute map to Cognito's attributes

#### Authenticate

Authenticates a user

If this method call succeeds the instance will have the following attributes **id_token**, **refresh_token**, **access_token**, **expires_in**, **expires_datetime**, and **token_type**.

```python
from pycognito import Cognito

u = Cognito('your-user-pool-id','your-client-id',
    username='bob')

u.authenticate(password='bobs-password')
```

##### Arguments

- **password:** - User's password

#### Admin Authenticate

Authenticate the user using admin super privileges

```python
from pycognito import Cognito

u = Cognito('your-user-pool-id','your-client-id',
    username='bob')

u.admin_authenticate(password='bobs-password')
```

- **password:** User's password

#### Initiate Forgot Password

Sends a verification code to the user to use to change their password.

```python
u = Cognito('your-user-pool-id','your-client-id',
    username='bob')

u.initiate_forgot_password()
```

##### Arguments

No arguments

#### Confirm Forgot Password

Allows a user to enter a code provided when they reset their password
to update their password.

```python
u = Cognito('your-user-pool-id','your-client-id',
    username='bob')

u.confirm_forgot_password('your-confirmation-code','your-new-password')
```

##### Arguments

- **confirmation_code:** The confirmation code sent by a user's request
  to retrieve a forgotten password
- **password:** New password

#### Change Password

Changes the user's password

```python
from pycognito import Cognito

#If you don't use your tokens then you will need to
#use your username and password and call the authenticate method
u = 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')
```

##### Arguments

- **previous_password:** - User's previous password
- **proposed_password:** - The password that the user wants to change to.

#### Confirm Sign Up

Use the confirmation code that is sent via email or text to confirm the user's account

```python
from pycognito import Cognito

u = Cognito('your-user-pool-id','your-client-id')

u.confirm_sign_up('users-conf-code',username='bob')
```

##### Arguments

- **confirmation_code:** Confirmation code sent via text or email
- **username:** User's username

#### Update Profile

Update the user's profile

```python
from pycognito import Cognito

u = 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())
```

##### Arguments

- **attrs:** Dictionary of attribute name, values
- **attr_map:** Dictionary map from Cognito attributes to attribute names we would like to show to our users

#### Send Verification

Send verification email or text for either the email or phone attributes.

```python
from pycognito import Cognito

u = 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')
```

##### Arguments

- **attribute:** - The attribute (email or phone) that needs to be verified

#### Get User Object

Returns an instance of the specified user_class.

```python
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"}
    )
```

##### Arguments

- **username:** Username of the user
- **attribute_list:** List of tuples that represent the user's attributes as returned by the admin_get_user or get_user boto3 methods
- **metadata: (optional)** Metadata about the user
- **attr_map: (optional)** Dictionary that maps the Cognito attribute names to what we'd like to display to the users

#### Get User

Get all of the user's attributes. Gets the user's attributes using Boto3 and uses that info to create an instance of the user_class

```python
from pycognito import Cognito

u = Cognito('your-user-pool-id','your-client-id',
    username='bob')

user = u.get_user(attr_map={"given_name":"first_name","family_name":"last_name"})
```

##### Arguments

- **attr_map:** Dictionary map from Cognito attributes to attribute names we would like to show to our users

#### Get Users

Get a list of the user in the user pool.

```python
from pycognito import Cognito

u = Cognito('your-user-pool-id','your-client-id')

user = u.get_users(attr_map={"given_name":"first_name","family_name":"last_name"})
```

##### Arguments

- **attr_map:** Dictionary map from Cognito attributes to attribute names we would like to show to our users

#### Get Group object

Returns an instance of the specified group_class.

```python
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)
```

##### Arguments

- **group_data:** Dictionary with group's attributes.

#### Get Group

Get all of the group's attributes. Returns an instance of the group_class.
Requires developer credentials.

```python
from pycognito import Cognito

u = Cognito('your-user-pool-id','your-client-id')

group = u.get_group(group_name='some_group_name')
```

##### Arguments

- **group_name:** Name of a group

#### Get Groups

Get a list of groups in the user pool. Requires developer credentials.

```python
from pycognito import Cognito

u = Cognito('your-user-pool-id','your-client-id')

groups = u.get_groups()
```

#### Check Token

Checks 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 required

```python
u = Cognito('your-user-pool-id','your-client-id',
    id_token='id-token',refresh_token='refresh-token',
    access_token='access-token')

u.check_token()
```

##### Arguments

No arguments for check_token

#### Verify Tokens

Verifies the current `id_token` and `access_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 the `Cognito()` constructor.
Note that if you're calling `check_tokens()` after instantitation, you'll still want to call `verify_tokens()` afterwards it in case it did nothing.
This method also ensures that the `id_claims` and `access_claims` attributes are set with the verified claims from each token.

```python
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 tokens
u.verify_tokens()
```

##### Arguments

No arguments for verify_tokens

#### Logout

Logs the user out of all clients and removes the expires_in, expires_datetime, id_token, refresh_token, access_token, and token_type attributes.

```python
from pycognito import Cognito

#If you don't use your tokens then you will need to
#use your username and password and call the authenticate method
u = Cognito('your-user-pool-id','your-client-id',
    id_token='id-token',refresh_token='refresh-token',
    access_token='access-token')

u.logout()
```

##### Arguments

No arguments for logout

#### Associate Software Token

Get 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.

```python
from pycognito import Cognito

#If you don't use your tokens then you will need to
#use your username and password and call the authenticate method
u = 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.
```

##### Arguments

No arguments for associate_software_token

#### Verify Software Token

Verify 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.

```python
from pycognito import Cognito

#If you don't use your tokens then you will need to
#use your username and password and call the authenticate method
u = 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)
```

##### Arguments

- **code:** 6-digit code generated by the TOTP generator app
- **device_name:** Name of a device

#### Set User MFA Preference

Enable and prioritize Software Token MFA and SMS MFA.
If both Software Token MFA and SMS MFA are invalid, the preference value will be ignored.

```python
from pycognito import Cognito

#If you don't use your tokens then you will need to
#use your username and password and call the authenticate method
u = 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 preference
u.set_user_mfa_preference(True, True, "SOFTWARE_TOKEN")
# Both Software Token MFA and SMS MFA are disabled.
u.set_user_mfa_preference(False, False)
```

##### Arguments

- **sms_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 challenge

Responds when a Software Token MFA challenge is requested at login.

```python
from pycognito import Cognito
from pycognito.exceptions import SoftwareTokenMFAChallengeException

#If you don't use your tokens then you will need to
#use your username and password and call the authenticate method
u = Cognito('your-user-pool-id','your-client-id',
    username='bob')

try:
    u.authenticate(password='bobs-password')
except SoftwareTokenMFAChallengeException as error:
    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 instance

```python
from pycognito import Cognito
from pycognito.exceptions import SoftwareTokenMFAChallengeException

#If you don't use your tokens then you will need to
#use your username and password and call the authenticate method
u = Cognito('your-user-pool-id','your-client-id',
    username='bob')

try:
    u.authenticate(password='bobs-password')
except SoftwareTokenMFAChallengeException as error:
    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)

```

##### Arguments

- **code:** 6-digit code generated by the TOTP generator app
- **mfa_tokens:** mfa_token stored in MFAChallengeException. Not required if you have not regenerated the Cognito instance.

#### Respond to SMS MFA challenge

Responds when a SMS MFA challenge is requested at login.

```python
from pycognito import Cognito
from pycognito.exceptions import SMSMFAChallengeException

#If you don't use your tokens then you will need to
#use your username and password and call the authenticate method
u = Cognito('your-user-pool-id','your-client-id',
    username='bob')

try:
    u.authenticate(password='bobs-password')
except SMSMFAChallengeException as error:
    code = input('Enter the 6-digit code you received by SMS.')
    u.respond_to_sms_mfa_challenge(code)
```

When recreating a Cognito instance

```python
from pycognito import Cognito
from pycognito.exceptions import SMSMFAChallengeException

#If you don't use your tokens then you will need to
#use your username and password and call the authenticate method
u = Cognito('your-user-pool-id','your-client-id',
    username='bob')

try:
    u.authenticate(password='bobs-password')
except SMSMFAChallengeException as error:
    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)

```

##### Arguments

- **code:** 6-digit code you received by SMS
- **mfa_tokens:** mfa_token stored in MFAChallengeException. Not required if you have not regenerated the Cognito instance.

## Cognito SRP Utility

The `AWSSRP` class is used to perform [SRP(Secure Remote Password protocol)](https://www.ietf.org/rfc/rfc2945.txt) 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 AWSSRP

The `AWSSRP` class 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 or `boto3` client.
Afterwards, the `authenticate_user` class method is used for SRP authentication.

```python
import boto3
from pycognito.aws_srp import AWSSRP

client = 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()
```

## SRP Requests Authenticator

`pycognito.utils.RequestsSrpAuth` is a [Requests](https://docs.python-requests.org/en/latest/)
authentication plugin to automatically populate an HTTP header with a Cognito token. By default, it'll populate
the `Authorization` header using the Cognito Access Token as a `bearer` token.

`RequestsSrpAuth` handles fetching new tokens using the refresh tokens.

### Usage

```python
import requests
from pycognito.utils import RequestsSrpAuth

auth = 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)
```

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/pvizeli/pycognito",
    "name": "pycognito",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "aws,cognito,api,gateway,serverless",
    "author": "Pascal Vizeli",
    "author_email": "pvizeli@syshack.ch",
    "download_url": "https://files.pythonhosted.org/packages/2e/3f/680674a3c85008d755661f5e8f7d6d769d944a068e9aafad45bef122c967/pycognito-2023.5.0.tar.gz",
    "platform": null,
    "description": "# pyCognito\n\nMakes working with AWS Cognito easier for Python developers.\n\n## Getting Started\n\n- [Python Versions Supported](#python-versions-supported)\n- [Install](#install)\n- [Environment Variables](#environment-variables)\n  - [COGNITO_JWKS](#cognito-jwks) (optional)\n- [Cognito Utility Class](#cognito-utility-class) `pycognito.Cognito`\n  - [Cognito Methods](#cognito-methods)\n    - [Register](#register)\n    - [Authenticate](#authenticate)\n    - [Admin Authenticate](#admin-authenticate)\n    - [Initiate Forgot Password](#initiate-forgot-password)\n    - [Confirm Forgot Password](#confirm-forgot-password)\n    - [Change Password](#change-password)\n    - [Confirm Sign Up](#confirm-sign-up)\n    - [Update Profile](#update-profile)\n    - [Send Verification](#send-verification)\n    - [Get User Object](#get-user-object)\n    - [Get User](#get-user)\n    - [Get Users](#get-users)\n    - [Get Group Object](#get-group-object)\n    - [Get Group](#get-group)\n    - [Get Groups](#get-groups)\n    - [Check Token](#check-token)\n    - [Verify Tokens](#verify-tokens)\n    - [Logout](#logout)\n    - [Associate Software Token](#associate-software-token)\n    - [Verify Software Token](#verify-software-token)\n    - [Set User MFA Preference](#set-user-mfa-preference)\n    - [Respond to Software Token MFA challenge](#respond-to-software-token-mfa-challenge)\n    - [Respond to SMS MFA challenge](#respond-to-sms-mfa-challenge)\n- [Cognito SRP Utility](#cognito-srp-utility)\n  - [Using AWSSRP](#using-awssrp)\n- [SRP Requests Authenticator](#srp-requests-authenticator)\n\n## Python Versions Supported\n\n- 3.6\n- 3.7\n- 3.8\n\n## Install\n\n`pip install pycognito`\n\n## Environment Variables\n\n#### COGNITO_JWKS\n\n**Optional:** 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.\n`https://cognito-idp.{aws-region}.amazonaws.com/{user-pool-id}/.well-known/jwks.json`\n\n**Example Value (Not Real):**\n\n```commandline\nCOGNITO_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\"}]}\n```\n\n## Cognito Utility Class\n\n### Example with All Arguments\n\n```python\nfrom pycognito import Cognito\n\nu = Cognito('your-user-pool-id','your-client-id',\n    client_secret='optional-client-secret'\n    username='optional-username',\n    id_token='optional-id-token',\n    refresh_token='optional-refresh-token',\n    access_token='optional-access-token',\n    access_key='optional-access-key',\n    secret_key='optional-secret-key')\n```\n\n#### Arguments\n\n- **user_pool_id:** Cognito User Pool ID\n- **client_id:** Cognito User Pool Application client ID\n- **client_secret:** App client secret (if app client is configured with client secret)\n- **username:** User Pool username\n- **id_token:** ID Token returned by authentication\n- **refresh_token:** Refresh Token returned by authentication\n- **access_token:** Access Token returned by authentication\n- **access_key:** AWS IAM access key\n- **secret_key:** AWS IAM secret key\n\n### Examples with Realistic Arguments\n\n#### User Pool Id and Client ID Only\n\nUsed when you only need information about the user pool (ex. list users in the user pool)\n\n```python\nfrom pycognito import Cognito\n\nu = Cognito('your-user-pool-id','your-client-id')\n```\n\n#### Username\n\nUsed 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).\n\n```python\nfrom pycognito import Cognito\n\nu = Cognito('your-user-pool-id','your-client-id',\n    username='bob')\n```\n\n#### Tokens\n\nUsed after the user has already authenticated and you need to build a new Cognito instance (ex. for use in a view).\n\n```python\nfrom pycognito import Cognito\n\nu = Cognito('your-user-pool-id','your-client-id',\n    id_token='your-id-token',\n    refresh_token='your-refresh-token',\n    access_token='your-access-token')\n\nu.verify_tokens() # See method doc below; may throw an exception\n```\n\n## Cognito Attributes\n\nAfter any authentication or other explicit verification of tokens, the following additional attributes will be available:\n\n- `id_claims` \u2014 A dict of verified claims from the id token\n- `access_claims` \u2014 A dict of verified claims from the access token\n\n## Cognito Methods\n\n#### Register\n\nRegister a user to the user pool\n\n**Important:** The arguments for `set_base_attributes` and `add_custom_attributes` methods 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.\n\n```python\nfrom pycognito import Cognito\n\nu = Cognito('your-user-pool-id', 'your-client-id')\n\nu.set_base_attributes(email='you@you.com', some_random_attr='random value')\n\nu.register('username', 'password')\n```\n\nRegister with custom attributes.\n\nFirstly, add custom attributes on 'General settings -> Attributes' page.\nSecondly, set permissions on 'Generals settings-> App clients-> Show details-> Set attribute read and write permissions' page.\n\n```python\nfrom pycognito import Cognito\n\nu = Cognito('your-user-pool-id', 'your-client-id')\n\nu.set_base_attributes(email='you@you.com', some_random_attr='random value')\n\nu.add_custom_attributes(state='virginia', city='Centreville')\n\nu.register('username', 'password')\n```\n\n##### Arguments\n\n- **username:** User Pool username\n- **password:** User Pool password\n- **attr_map:** Attribute map to Cognito's attributes\n\n#### Authenticate\n\nAuthenticates a user\n\nIf this method call succeeds the instance will have the following attributes **id_token**, **refresh_token**, **access_token**, **expires_in**, **expires_datetime**, and **token_type**.\n\n```python\nfrom pycognito import Cognito\n\nu = Cognito('your-user-pool-id','your-client-id',\n    username='bob')\n\nu.authenticate(password='bobs-password')\n```\n\n##### Arguments\n\n- **password:** - User's password\n\n#### Admin Authenticate\n\nAuthenticate the user using admin super privileges\n\n```python\nfrom pycognito import Cognito\n\nu = Cognito('your-user-pool-id','your-client-id',\n    username='bob')\n\nu.admin_authenticate(password='bobs-password')\n```\n\n- **password:** User's password\n\n#### Initiate Forgot Password\n\nSends a verification code to the user to use to change their password.\n\n```python\nu = Cognito('your-user-pool-id','your-client-id',\n    username='bob')\n\nu.initiate_forgot_password()\n```\n\n##### Arguments\n\nNo arguments\n\n#### Confirm Forgot Password\n\nAllows a user to enter a code provided when they reset their password\nto update their password.\n\n```python\nu = Cognito('your-user-pool-id','your-client-id',\n    username='bob')\n\nu.confirm_forgot_password('your-confirmation-code','your-new-password')\n```\n\n##### Arguments\n\n- **confirmation_code:** The confirmation code sent by a user's request\n  to retrieve a forgotten password\n- **password:** New password\n\n#### Change Password\n\nChanges the user's password\n\n```python\nfrom pycognito import Cognito\n\n#If you don't use your tokens then you will need to\n#use your username and password and call the authenticate method\nu = Cognito('your-user-pool-id','your-client-id',\n    id_token='id-token',refresh_token='refresh-token',\n    access_token='access-token')\n\nu.change_password('previous-password','proposed-password')\n```\n\n##### Arguments\n\n- **previous_password:** - User's previous password\n- **proposed_password:** - The password that the user wants to change to.\n\n#### Confirm Sign Up\n\nUse the confirmation code that is sent via email or text to confirm the user's account\n\n```python\nfrom pycognito import Cognito\n\nu = Cognito('your-user-pool-id','your-client-id')\n\nu.confirm_sign_up('users-conf-code',username='bob')\n```\n\n##### Arguments\n\n- **confirmation_code:** Confirmation code sent via text or email\n- **username:** User's username\n\n#### Update Profile\n\nUpdate the user's profile\n\n```python\nfrom pycognito import Cognito\n\nu = Cognito('your-user-pool-id','your-client-id',\n    id_token='id-token',refresh_token='refresh-token',\n    access_token='access-token')\n\nu.update_profile({'given_name':'Edward','family_name':'Smith',},attr_map=dict())\n```\n\n##### Arguments\n\n- **attrs:** Dictionary of attribute name, values\n- **attr_map:** Dictionary map from Cognito attributes to attribute names we would like to show to our users\n\n#### Send Verification\n\nSend verification email or text for either the email or phone attributes.\n\n```python\nfrom pycognito import Cognito\n\nu = Cognito('your-user-pool-id','your-client-id',\n    id_token='id-token',refresh_token='refresh-token',\n    access_token='access-token')\n\nu.send_verification(attribute='email')\n```\n\n##### Arguments\n\n- **attribute:** - The attribute (email or phone) that needs to be verified\n\n#### Get User Object\n\nReturns an instance of the specified user_class.\n\n```python\nu = Cognito('your-user-pool-id','your-client-id',\n    id_token='id-token',refresh_token='refresh-token',\n    access_token='access-token')\n\nu.get_user_obj(username='bjones',\n    attribute_list=[{'Name': 'string','Value': 'string'},],\n    metadata={},\n    attr_map={\"given_name\":\"first_name\",\"family_name\":\"last_name\"}\n    )\n```\n\n##### Arguments\n\n- **username:** Username of the user\n- **attribute_list:** List of tuples that represent the user's attributes as returned by the admin_get_user or get_user boto3 methods\n- **metadata: (optional)** Metadata about the user\n- **attr_map: (optional)** Dictionary that maps the Cognito attribute names to what we'd like to display to the users\n\n#### Get User\n\nGet all of the user's attributes. Gets the user's attributes using Boto3 and uses that info to create an instance of the user_class\n\n```python\nfrom pycognito import Cognito\n\nu = Cognito('your-user-pool-id','your-client-id',\n    username='bob')\n\nuser = u.get_user(attr_map={\"given_name\":\"first_name\",\"family_name\":\"last_name\"})\n```\n\n##### Arguments\n\n- **attr_map:** Dictionary map from Cognito attributes to attribute names we would like to show to our users\n\n#### Get Users\n\nGet a list of the user in the user pool.\n\n```python\nfrom pycognito import Cognito\n\nu = Cognito('your-user-pool-id','your-client-id')\n\nuser = u.get_users(attr_map={\"given_name\":\"first_name\",\"family_name\":\"last_name\"})\n```\n\n##### Arguments\n\n- **attr_map:** Dictionary map from Cognito attributes to attribute names we would like to show to our users\n\n#### Get Group object\n\nReturns an instance of the specified group_class.\n\n```python\nu = Cognito('your-user-pool-id', 'your-client-id')\n\ngroup_data = {'GroupName': 'user_group', 'Description': 'description',\n            'Precedence': 1}\n\ngroup_obj = u.get_group_obj(group_data)\n```\n\n##### Arguments\n\n- **group_data:** Dictionary with group's attributes.\n\n#### Get Group\n\nGet all of the group's attributes. Returns an instance of the group_class.\nRequires developer credentials.\n\n```python\nfrom pycognito import Cognito\n\nu = Cognito('your-user-pool-id','your-client-id')\n\ngroup = u.get_group(group_name='some_group_name')\n```\n\n##### Arguments\n\n- **group_name:** Name of a group\n\n#### Get Groups\n\nGet a list of groups in the user pool. Requires developer credentials.\n\n```python\nfrom pycognito import Cognito\n\nu = Cognito('your-user-pool-id','your-client-id')\n\ngroups = u.get_groups()\n```\n\n#### Check Token\n\nChecks 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 required\n\n```python\nu = Cognito('your-user-pool-id','your-client-id',\n    id_token='id-token',refresh_token='refresh-token',\n    access_token='access-token')\n\nu.check_token()\n```\n\n##### Arguments\n\nNo arguments for check_token\n\n#### Verify Tokens\n\nVerifies the current `id_token` and `access_token`.\nAn exception will be thrown if they do not pass verification.\nIt can be useful to call this method immediately after instantiation when you're providing externally-remembered tokens to the `Cognito()` constructor.\nNote that if you're calling `check_tokens()` after instantitation, you'll still want to call `verify_tokens()` afterwards it in case it did nothing.\nThis method also ensures that the `id_claims` and `access_claims` attributes are set with the verified claims from each token.\n\n```python\nu = Cognito('your-user-pool-id','your-client-id',\n    id_token='id-token',refresh_token='refresh-token',\n    access_token='access-token')\n\nu.check_tokens()  # Optional, if you want to maybe renew the tokens\nu.verify_tokens()\n```\n\n##### Arguments\n\nNo arguments for verify_tokens\n\n#### Logout\n\nLogs the user out of all clients and removes the expires_in, expires_datetime, id_token, refresh_token, access_token, and token_type attributes.\n\n```python\nfrom pycognito import Cognito\n\n#If you don't use your tokens then you will need to\n#use your username and password and call the authenticate method\nu = Cognito('your-user-pool-id','your-client-id',\n    id_token='id-token',refresh_token='refresh-token',\n    access_token='access-token')\n\nu.logout()\n```\n\n##### Arguments\n\nNo arguments for logout\n\n#### Associate Software Token\n\nGet the secret code to issue the software token MFA code.\nBegins setup of time-based one-time password (TOTP) multi-factor authentication (MFA) for a user.\n\n```python\nfrom pycognito import Cognito\n\n#If you don't use your tokens then you will need to\n#use your username and password and call the authenticate method\nu = Cognito('your-user-pool-id','your-client-id',\n    id_token='id-token',refresh_token='refresh-token',\n    access_token='access-token')\n\nsecret_code = u.associate_software_token()\n# 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.\n```\n\n##### Arguments\n\nNo arguments for associate_software_token\n\n#### Verify Software Token\n\nVerify 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.\n\n```python\nfrom pycognito import Cognito\n\n#If you don't use your tokens then you will need to\n#use your username and password and call the authenticate method\nu = Cognito('your-user-pool-id','your-client-id',\n    id_token='id-token',refresh_token='refresh-token',\n    access_token='access-token')\n\nsecret_code = u.associate_software_token()\n# 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.\ncode = input('Enter the 6-digit code.')\ndevice_name = input('Enter the device name')\nu.verify_software_token(code, device_name)\n```\n\n##### Arguments\n\n- **code:** 6-digit code generated by the TOTP generator app\n- **device_name:** Name of a device\n\n#### Set User MFA Preference\n\nEnable and prioritize Software Token MFA and SMS MFA.\nIf both Software Token MFA and SMS MFA are invalid, the preference value will be ignored.\n\n```python\nfrom pycognito import Cognito\n\n#If you don't use your tokens then you will need to\n#use your username and password and call the authenticate method\nu = Cognito('your-user-pool-id','your-client-id',\n    id_token='id-token',refresh_token='refresh-token',\n    access_token='access-token')\n\n# SMS MFA are valid. SMS preference.\nu.set_user_mfa_preference(True, False, \"SMS\")\n# Software Token MFA are valid. Software token preference.\nu.set_user_mfa_preference(False, True, \"SOFTWARE_TOKEN\")\n# Both Software Token MFA and SMS MFA are valid. Software token preference\nu.set_user_mfa_preference(True, True, \"SOFTWARE_TOKEN\")\n# Both Software Token MFA and SMS MFA are disabled.\nu.set_user_mfa_preference(False, False)\n```\n\n##### Arguments\n\n- **sms_mfa:** SMS MFA enabled / disabled (bool)\n- **software_token_mfa:** Software Token MFA enabled / disabled (bool)\n- **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.\n\n#### Respond to Software Token MFA challenge\n\nResponds when a Software Token MFA challenge is requested at login.\n\n```python\nfrom pycognito import Cognito\nfrom pycognito.exceptions import SoftwareTokenMFAChallengeException\n\n#If you don't use your tokens then you will need to\n#use your username and password and call the authenticate method\nu = Cognito('your-user-pool-id','your-client-id',\n    username='bob')\n\ntry:\n    u.authenticate(password='bobs-password')\nexcept SoftwareTokenMFAChallengeException as error:\n    code = input('Enter the 6-digit code generated by the TOTP generator (such as Google Authenticator).')\n    u.respond_to_software_token_mfa_challenge(code)\n```\n\nWhen recreating a Cognito instance\n\n```python\nfrom pycognito import Cognito\nfrom pycognito.exceptions import SoftwareTokenMFAChallengeException\n\n#If you don't use your tokens then you will need to\n#use your username and password and call the authenticate method\nu = Cognito('your-user-pool-id','your-client-id',\n    username='bob')\n\ntry:\n    u.authenticate(password='bobs-password')\nexcept SoftwareTokenMFAChallengeException as error:\n    mfa_tokens = error.get_tokens()\n\nu = Cognito('your-user-pool-id','your-client-id',\n    username='bob')\ncode = input('Enter the 6-digit code generated by the TOTP generator (such as Google Authenticator).')\nu.respond_to_software_token_mfa_challenge(code, mfa_tokens)\n\n```\n\n##### Arguments\n\n- **code:** 6-digit code generated by the TOTP generator app\n- **mfa_tokens:** mfa_token stored in MFAChallengeException. Not required if you have not regenerated the Cognito instance.\n\n#### Respond to SMS MFA challenge\n\nResponds when a SMS MFA challenge is requested at login.\n\n```python\nfrom pycognito import Cognito\nfrom pycognito.exceptions import SMSMFAChallengeException\n\n#If you don't use your tokens then you will need to\n#use your username and password and call the authenticate method\nu = Cognito('your-user-pool-id','your-client-id',\n    username='bob')\n\ntry:\n    u.authenticate(password='bobs-password')\nexcept SMSMFAChallengeException as error:\n    code = input('Enter the 6-digit code you received by SMS.')\n    u.respond_to_sms_mfa_challenge(code)\n```\n\nWhen recreating a Cognito instance\n\n```python\nfrom pycognito import Cognito\nfrom pycognito.exceptions import SMSMFAChallengeException\n\n#If you don't use your tokens then you will need to\n#use your username and password and call the authenticate method\nu = Cognito('your-user-pool-id','your-client-id',\n    username='bob')\n\ntry:\n    u.authenticate(password='bobs-password')\nexcept SMSMFAChallengeException as error:\n    mfa_tokens = error.get_tokens()\n\nu = Cognito('your-user-pool-id','your-client-id',\n    username='bob')\ncode = input('Enter the 6-digit code generated by the TOTP generator (such as Google Authenticator).')\nu.respond_to_sms_mfa_challenge(code, mfa_tokens)\n\n```\n\n##### Arguments\n\n- **code:** 6-digit code you received by SMS\n- **mfa_tokens:** mfa_token stored in MFAChallengeException. Not required if you have not regenerated the Cognito instance.\n\n## Cognito SRP Utility\n\nThe `AWSSRP` class is used to perform [SRP(Secure Remote Password protocol)](https://www.ietf.org/rfc/rfc2945.txt) authentication.\nThis is the preferred method of user authentication with AWS Cognito.\nThe process involves a series of authentication challenges and responses, which if successful,\nresults in a final response that contains ID, access and refresh tokens.\n\n### Using AWSSRP\n\nThe `AWSSRP` class takes a username, password, cognito user pool id, cognito app id, an optional\nclient secret (if app client is configured with client secret), an optional pool_region or `boto3` client.\nAfterwards, the `authenticate_user` class method is used for SRP authentication.\n\n```python\nimport boto3\nfrom pycognito.aws_srp import AWSSRP\n\nclient = boto3.client('cognito-idp')\naws = AWSSRP(username='username', password='password', pool_id='user_pool_id',\n             client_id='client_id', client=client)\ntokens = aws.authenticate_user()\n```\n\n## SRP Requests Authenticator\n\n`pycognito.utils.RequestsSrpAuth` is a [Requests](https://docs.python-requests.org/en/latest/)\nauthentication plugin to automatically populate an HTTP header with a Cognito token. By default, it'll populate\nthe `Authorization` header using the Cognito Access Token as a `bearer` token.\n\n`RequestsSrpAuth` handles fetching new tokens using the refresh tokens.\n\n### Usage\n\n```python\nimport requests\nfrom pycognito.utils import RequestsSrpAuth\n\nauth = RequestsSrpAuth(\n  username='myusername',\n  password='secret',\n  user_pool_id='eu-west-1_1234567',\n  client_id='4dn6jbcbhqcofxyczo3ms9z4cc',\n  user_pool_region='eu-west-1',\n)\n\nresponse = requests.get('http://test.com', auth=auth)\n```\n",
    "bugtrack_url": null,
    "license": "Apache License 2.0",
    "summary": "Python class to integrate Boto3's Cognito client so it is easy to login users. With SRP support.",
    "version": "2023.5.0",
    "project_urls": {
        "Download": "https://github.com/pvizeli/pycognito/tarball/2023.5.0",
        "Homepage": "https://github.com/pvizeli/pycognito"
    },
    "split_keywords": [
        "aws",
        "cognito",
        "api",
        "gateway",
        "serverless"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "7d82ae4cc4d88ff07c460e70f937044813a6fb2f5cbeffc5c54f666651e62b37",
                "md5": "2c2fc0cc9a7ec7658e1bb0c90782ea23",
                "sha256": "0a73c2bdc966465df3a61cba445f58beee9734638be7b10681792725651168eb"
            },
            "downloads": -1,
            "filename": "pycognito-2023.5.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "2c2fc0cc9a7ec7658e1bb0c90782ea23",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 24222,
            "upload_time": "2023-05-26T13:41:56",
            "upload_time_iso_8601": "2023-05-26T13:41:56.856409Z",
            "url": "https://files.pythonhosted.org/packages/7d/82/ae4cc4d88ff07c460e70f937044813a6fb2f5cbeffc5c54f666651e62b37/pycognito-2023.5.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "2e3f680674a3c85008d755661f5e8f7d6d769d944a068e9aafad45bef122c967",
                "md5": "4fc1dd7f788523e8ac1cd638acdc6c7b",
                "sha256": "3843cfff56969f7c4b0b2fd499877941d0bf33e39c4541dc896c2b83bef5db24"
            },
            "downloads": -1,
            "filename": "pycognito-2023.5.0.tar.gz",
            "has_sig": false,
            "md5_digest": "4fc1dd7f788523e8ac1cd638acdc6c7b",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 27993,
            "upload_time": "2023-05-26T13:41:58",
            "upload_time_iso_8601": "2023-05-26T13:41:58.864995Z",
            "url": "https://files.pythonhosted.org/packages/2e/3f/680674a3c85008d755661f5e8f7d6d769d944a068e9aafad45bef122c967/pycognito-2023.5.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-05-26 13:41:58",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "pvizeli",
    "github_project": "pycognito",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "pycognito"
}
        
Elapsed time: 0.08272s