Python类,用于集成Boto3的Cognito客户端,以便更容易地登录用户。支持SRP。
项目描述
pyCognito
使Python开发者更容易使用AWS Cognito。
入门
- 支持的Python版本
- 安装
- 环境变量
- COGNITO_JWKS (可选)
- Cognito实用类
pycognito.Cognito
- Cognito SRP实用工具
- 设备认证支持
- SRP请求认证器
支持的Python版本
- 3.8
- 3.9
- 3.10
- 3.11
- 3.12
安装
pip安装pycognito
环境变量
COGNITO_JWKS
可选:此环境变量是一个字典,代表由 AWS Cognito 分配给您的用户池的已知 JWK。您可以通过将以下示例中的 AWS 区域和用户池 ID 替换为您的实际值来找到您的用户池的密钥。https://cognito-idp.{aws-region}.amazonaws.com/{user-pool-id}/.well-known/jwks.json
示例值(非真实)
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 工具类
所有参数的示例
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')
参数
- user_pool_id: Cognito 用户池 ID
- client_id: Cognito 用户池应用程序客户端 ID
- client_secret: 应用客户端密钥(如果应用程序客户端配置了客户端密钥)
- username: 用户池用户名
- id_token: 认证返回的 ID 令牌
- refresh_token: 认证返回的刷新令牌
- access_token: 认证返回的访问令牌
- access_key: AWS IAM 访问密钥
- secret_key: AWS IAM 密钥
使用现实参数的示例
仅用户池 ID 和客户端 ID
当您只需要有关用户池的信息时使用(例如列出用户池中的用户)
from pycognito import Cognito
u = Cognito('your-user-pool-id','your-client-id')
用户名
当用户尚未登录时使用。当您计划使用 SRP(认证)或 admin_authenticate(admin_initiate_auth)进行认证时,请从这些参数开始。
from pycognito import Cognito
u = Cognito('your-user-pool-id','your-client-id',
username='bob')
令牌
在用户已经认证后使用,您需要构建一个新的 Cognito 实例(例如用于视图)。
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 属性
在完成任何认证或其他显式令牌验证之后,以下附加属性将可用
id_claims
— ID 令牌中的验证声明字典access_claims
— 访问令牌中的验证声明字典
Cognito方法
注册
将用户注册到用户池
注意:对于 set_base_attributes
和 add_custom_attributes
方法的参数取决于您的用户池配置,并确保使用的客户端 ID(应用程序 ID)具有对您要创建的属性的写权限。例如,如果您想创建一个 given_name 等于 Johnson 的用户,请确保您使用的客户端 ID 有权限编辑或创建池中用户的 given_name。
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')
使用自定义属性进行注册。
首先,在“常规设置 -> 属性”页面上添加自定义属性。其次,在“常规设置 -> 应用客户端 -> 显示详细信息 -> 设置属性读写权限”页面上设置权限。
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')
参数
- username: 用户池用户名
- password: 用户池密码
- attr_map: 属性映射到 Cognito 属性
认证
认证用户
如果此方法调用成功,实例将具有以下属性 id_token、refresh_token、access_token、expires_in、expires_datetime 和 token_type。
from pycognito import Cognito
u = Cognito('your-user-pool-id','your-client-id',
username='bob')
u.authenticate(password='bobs-password')
参数
- password: - 用户的密码
管理员认证
使用管理员超级权限认证用户
from pycognito import Cognito
u = Cognito('your-user-pool-id','your-client-id',
username='bob')
u.admin_authenticate(password='bobs-password')
- password: 用户的密码
启动忘记密码
向用户发送验证码以供他们更改密码使用。
u = Cognito('your-user-pool-id','your-client-id',
username='bob')
u.initiate_forgot_password()
参数
无参数
确认忘记密码
允许用户输入他们重置密码时提供的代码以更新他们的密码。
u = Cognito('your-user-pool-id','your-client-id',
username='bob')
u.confirm_forgot_password('your-confirmation-code','your-new-password')
参数
- confirmation_code: 用户请求恢复忘记的密码时发送的确认码
- password: 新密码
更改密码
更改用户的密码
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')
参数
- previous_password: - 用户的旧密码
- proposed_password: - 用户想要更改到的密码。
确认注册
使用通过电子邮件或短信发送的确认码来确认用户帐户
from pycognito import Cognito
u = Cognito('your-user-pool-id','your-client-id')
u.confirm_sign_up('users-conf-code',username='bob')
参数
- confirmation_code: 通过短信或电子邮件发送的确认码
- username: 用户名
更新个人资料
更新用户的个人资料
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())
参数
- attrs: 属性名称和值的字典
- attr_map: 从 Cognito 属性到我们希望向用户显示的属性名称的映射字典
发送验证
为电子邮件或电话属性发送验证电子邮件或短信。
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')
参数
- attribute: - 需要验证的属性(电子邮件或电话)
获取用户对象
返回指定用户类的实例。
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"}
)
参数
- username: 用户的用户名
- attribute_list: 表示用户属性(由admin_get_user或get_user boto3方法返回)的元组列表
- metadata: (可选) 用户的相关元数据
- attr_map: (可选) 将Cognito属性名称映射为我们希望向用户显示的内容的字典
获取用户
获取所有用户属性。使用Boto3获取用户的属性,并使用这些信息创建一个user_class实例
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"})
参数
- attr_map: 从 Cognito 属性到我们希望向用户显示的属性名称的映射字典
获取用户列表
获取用户池中用户的列表。
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"})
参数
- attr_map: 从 Cognito 属性到我们希望向用户显示的属性名称的映射字典
获取组对象
返回指定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)
参数
- group_data: 包含组属性的字典。
获取组
获取所有组的属性。返回group_class的实例。需要开发者凭据。
from pycognito import Cognito
u = Cognito('your-user-pool-id','your-client-id')
group = u.get_group(group_name='some_group_name')
参数
- group_name: 组的名称
获取组列表
获取用户池中所有组的列表。需要开发者凭据。
from pycognito import Cognito
u = Cognito('your-user-pool-id','your-client-id')
groups = u.get_groups()
检查令牌
检查access_token的exp属性,并通过调用renew_access_tokens方法刷新令牌,或者什么都不做。 重要: 需要access token
u = Cognito('your-user-pool-id','your-client-id',
id_token='id-token',refresh_token='refresh-token',
access_token='access-token')
u.check_token()
参数
check_token没有参数
验证令牌
验证当前的id_token
和access_token
。如果它们未通过验证,将抛出异常。当您向Cognito()
构造函数提供外部存储的令牌时,在实例化后立即调用此方法可能很有用。请注意,如果您在实例化后调用check_tokens()
,您仍然需要在之后调用verify_tokens()
,以防它什么都没做。此方法还确保了id_claims
和access_claims
属性被设置为每个令牌中验证的声明。
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()
参数
verify_tokens没有参数
登出
使用户在所有客户端注销并删除expires_in、expires_datetime、id_token、refresh_token、access_token和token_type属性。
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()
参数
logout没有参数
关联软件令牌
获取用于发行软件令牌MFA代码的秘密代码。为用户开始设置基于时间的单次密码(TOTP)多因素认证(MFA)。
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.
参数
associate_software_token没有参数
验证软件令牌
验证基于由associate_software_token发行的秘密代码发出的6位代码。如果此验证成功,Cognito将启用软件令牌MFA。
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)
参数
- code: 由TOTP生成器应用程序生成的6位代码
- device_name: 设备的名称
设置用户MFA偏好
启用并优先考虑软件令牌MFA和短信MFA。如果两者都无效,则忽略优先级值。
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)
参数
- sms_mfa: SMS MFA启用/禁用(布尔值)
- software_token_mfa: 软件令牌MFA启用/禁用(布尔值)
- preferred: 优先级是什么,SMS还是软件令牌?预期值是"SMS"或"SOFTWARE_TOKEN"。然而,如果前两个参数都是False,则不需要它。
响应软件令牌MFA挑战
在登录时请求软件令牌MFA挑战时做出响应。
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)
在重新创建Cognito实例时
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)
参数
- code: 由TOTP生成器应用程序生成的6位代码
- mfa_tokens: 存储在MFAChallengeException中的mfa_token。如果没有重新生成Cognito实例,则不需要。
响应短信MFA挑战
在登录时请求短信MFA挑战时做出响应。
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)
在重新创建Cognito实例时
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)
参数
- code: 通过短信收到的6位代码
- mfa_tokens: 存储在MFAChallengeException中的mfa_token。如果没有重新生成Cognito实例,则不需要。
Cognito SRP实用工具
AWSSRP
类用于执行SRP(安全远程密码协议)认证。这是AWS Cognito中用户认证的首选方法。该过程涉及一系列认证挑战和响应,如果成功,将得到一个最终响应,其中包含ID、访问和刷新令牌。
使用AWSSRP
AWSSRP
类接受用户名、密码、Cognito用户池ID、Cognito应用ID、可选的客户端密钥(如果应用客户端配置了客户端密钥)、可选的pool_region或boto3
客户端。之后,使用authenticate_user
类方法进行SRP认证。
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()
设备认证支持
您必须使用 USER_SRP_AUTH
认证流程来使用设备跟踪功能。更多关于 已记住的设备 的信息。
接收DeviceKey和DeviceGroupKey
一旦使用 authenticate_user
类方法进行 SRP 认证,响应还会返回 DeviceKey
和 DeviceGrouKey
。这些密钥将用于稍后确认设备。
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()
device_key = tokens["AuthenticationResult"]["NewDeviceMetadata"]["DeviceKey"]
device_group_key = tokens["AuthenticationResult"]["NewDeviceMetadata"]["DeviceGroupKey"]
确认设备
使用 confirm_device
类方法来确认设备,它需要两个输入:tokens
和 DeviceName
(DeviceName
是可选的)。该方法返回两个值:response
和 device_password
。稍后,将使用 device_password
来使用 Cognito 用户池进行设备认证。
response, device_password = user.confirm_device(tokens=tokens)
更新设备状态
使用 update_device_status
类方法来更新设备是否应该被记住。此方法需要三个输入:is_remembered
、access_token
和 device_key
。is_remembered
是一个布尔值,在 True
时将设备状态设置为 "remembered"
,在 False
时设置为 "not_remembered"
,access_token
是 Cognito 提供的访问令牌,device_key
是 authenticate_user
方法提供的密钥。
response = user.update_device_status(False, tokens["AuthenticationResult"]["AccessToken"], device_key)
认证您的设备
要认证您的设备,您只需将 device_key
、device_group_key
和 device_password
添加到 AWSSRP 类中。
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, device_key="device_key",
device_group_key="device_group_key", device_password="device_password")
tokens = aws.authenticate_user()
忘记设备
要忘记设备,您可以调用 forget_device
类方法。它需要 access_token
和 device_key
作为输入。
resonse = aws.forget_device(access_token='access_token', device_key='device_key')
SRP请求认证器
pycognito.utils.RequestsSrpAuth
是一个 Requests 认证插件,可自动用 Cognito 令牌填充 HTTP 头。默认情况下,它将使用 Cognito 访问令牌作为 bearer
令牌填充 Authorization
头。
RequestsSrpAuth
处理使用刷新令牌获取新令牌。
用法
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)
项目详情
下载文件
下载您平台的文件。如果您不确定要选择哪个,请了解更多关于 安装包 的信息。
源分布
构建分布
pycognito-2024.5.1.tar.gz 的散列
算法 | 散列摘要 | |
---|---|---|
SHA256 | e211c66698c2c3dc8680e95107c2b4a922f504c3f7c179c27b8ee1ab0fc23ae4 |
|
MD5 | 56c67d5040c5a5581d2f1463193a5861 |
|
BLAKE2b-256 | 26673975cf257fcc04903686ef87d39be386d894a0d8182f43d37e9cbfc9609f |