如何使用Python SDK为Cognito用户添加组

时间:2017-08-09 06:04:46

标签: python-2.7 amazon-web-services boto3 amazon-cognito aws-cognito

我正在尝试将用户添加到cognito并为其分配一个组。添加到组是成功的,但我无法添加到用户所属的组。

import boto3

email = 'test@test.test'
poolId = 'ap-northeast-1_xxxxxx'
group = 'xxxx'
password = 'String1234'
aws_access_key_id = 'Axxxxxxxx'
aws_secret_access_key = '6xxxxxxxxx'

session = boto3.Session(aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key)
client = session.client('cognito-idp')

response = client.admin_create_user(
                UserPoolId=poolId,
                Username=email,
                TemporaryPassword= password,
                UserAttributes=[

                    {
                        "Name": "email",
                        "Value": email
                    },
                    {
                        "Name": "email_verified",
                        "Value": "true"
                    }
                ]
            )

response = client.admin_add_user_to_group(
                UserPoolId=poolId,
                Username=email,
                GroupName=group
            )

成功添加用户但未添加组:

Traceback (most recent call last):   File "test.py", line 24, in <module>
response = client.admin_add_user_to_group
( AttributeError: 'CognitoIdentityProvider' object has no attribute 'admin_add_user_to_group'

在我的requirements.txt中为python创建虚拟环境我使用

boto3==1.4.5

使用this boto3文档作为参考。

1 个答案:

答案 0 :(得分:2)

我已经使用了boto3(1.4.6)。您在那里的示例我希望假设您已创建了您尝试将用户添加到的组。此外,以下代码示例假定您已将访问密钥,密钥作为环境变量导出。

import boto3
a='XXXXXXXXXXXXXXXXXXXX'
s='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
r='us-west-2'

session = boto3.Session(aws_access_key_id=a, aws_secret_access_key=s, region_name=r)
client = boto3.client('cognito-idp', region_name=r)

email = 'tes1t@test1.test'
poolId = 'us-west-2_xxxxxxxxx'
group = 'foo'
password = 'String1234'

response = client.admin_create_user(
                UserPoolId=poolId,
                Username=email,
                TemporaryPassword= password,
                UserAttributes=[{"Name": "email","Value": email}, { "Name": "email_verified", "Value": "true" }]
            )

reply = client.create_group(UserPoolId=poolId,  GroupName=group)
reply = client.admin_add_user_to_group( UserPoolId=poolId, Username=email, GroupName=group )