【问题标题】:NoCredentialsError when connecting to Cognito with Python and boto3使用 Python 和 boto3 连接到 Cognito 时出现 NoCredentialsError
【发布时间】:2016-09-16 23:33:02
【问题描述】:

我正在尝试运行一个简单的 AWS Cognito 实例。我创建了联合身份,并为经过身份验证和未经身份验证的用户分配了一个角色。我正在尝试连接到 Python 中的身份,但收到错误消息:

NoCredentialsError:无法找到凭据

我肯定使用了正确的 IdentityId,因为我直接从 AWS 控制台为您生成的代码示例中复制了它。我正在使用以下代码:

import boto3
identity = boto3.client('cognito-identity', 
                        region_name='us-east-1')

response = identity.describe_identity(IdentityId='us-east-1:XXXX')
print (response['IdentityId'])

如果我尝试检索凭据,则会收到以下错误:

ClientError:调用 GetCredentialsForIdentity 操作时发生错误 (ResourceNotFoundException):未找到 Identity 'us-east-1:XXXXXX'。

使用此代码:

import boto3
identity = boto3.client('cognito-identity', 
                        region_name='us-east-1')

response = identity.get_credentials_for_identity(IdentityId='us-east-1:XXXXX')
access_key = response['Credentials']['AccessKeyId']
secret_key = response['Credentials']['SecretKey']

print (access_key)
print (secret_key)

我还应该注意,如果我使用访问密钥和秘密创建身份客户端,我仍然会收到此处描述的第二个错误,但在这两种情况下。据我所知,我应该需要提供这些凭据,但我已经尝试过了。

【问题讨论】:

    标签: python python-3.x amazon-web-services amazon-cognito boto3


    【解决方案1】:

    Cognito 控制台不会为您生成身份 id,它会生成身份 pool id。如果您将其用作身份标识,那就是问题所在,它不会找到它。在这种情况下,您需要生成一个身份 ID(使用 GetId API)并使用它,然后使用该 ID 来获取凭据。

    【讨论】:

    • 您是否知道如何使用检索到的凭据通过 Python 调用 API 网关?我希望 boto3 库有办法处理这个签名过程,但我对其他问题不太满意:stackoverflow.com/questions/37336286/…
    【解决方案2】:

    扩展@jeff-bailey 很好的答案,这里是关于如何实现作者要求的完整示例代码:

    import boto3
    
    client = boto3.client('cognito-identity', region_name='eu-west-1')
    
    identity_pool_id = 'eu-west-1:a2342392-1391-191-1111111'
    response = client.get_id(AccountId='7778718191', IdentityPoolId=identity_pool_id)
    
    identity_id = response['IdentityId']
    print("Federated identity id:", identity_id)
    
    response = client.get_credentials_for_identity(IdentityId=identity_id)
    access_key = response['Credentials']['AccessKeyId']
    secret_key = response['Credentials']['SecretKey']
    
    print(access_key, secret_key)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-13
      • 2017-08-21
      • 2017-05-22
      • 1970-01-01
      • 2015-05-13
      • 2019-07-01
      • 2020-04-14
      • 2016-11-15
      相关资源
      最近更新 更多