【问题标题】:How to get authenticated identity response from AWS Cognito using boto3如何使用 boto3 从 AWS Cognito 获取经过身份验证的身份响应
【发布时间】:2019-09-13 06:03:29
【问题描述】:

我想使用 boto3 获取访问 AWS 服务的临时凭证。用例如下:我的 Cognito 用户池中的用户登录到我的服务器,我希望服务器代码为该用户提供访问其他 AWS 服务的临时凭证。

我有一个 Cognito 用户池,用于存储我的用户。我有一个 Cognito 身份池,它不允许未经授权的访问,只允许来自 Cognito 用户池的用户访问。

所以这是我开始的代码:

import boto3
client = boto3.client('cognito-identity','us-west-2')
resp = client.get_id(AccountId='<ACCNTID>',
                     IdentityPoolId='<IDPOOLID>')

但是,仅仅运行这三行代码就会抛出异常:

botocore.errorfactory.NotAuthorizedException: An error 
occurred (NotAuthorizedException) when calling 
the GetId operation: Unauthenticated access is not 
supported for this identity pool.

由于我的 Cognito 身份池没有设置为未经身份验证的访问,我似乎无法调用 get_id,直到我以某种方式在某处进行身份验证。

我该如何解决这个问题?我究竟需要做什么来进行身份验证才能调用 get_id?

更新:看起来我需要将登录字段和数据传递给 get_id 函数调用,但为此我需要登录 JWT 令牌。如果我在使用 AWS Cognito 预打包登录屏幕的 web 应用程序(例如 Django 后端)中运行它,那么是的,我可以在从成功登录重定向后从主页 URL 获取它。但是现在我正在编写一些与网站无关的测试脚本。有没有办法使用 boto 或 boto3 或其他 python 包使用用户名和密码登录并获取 JWT 令牌?

【问题讨论】:

    标签: python boto3 amazon-cognito


    【解决方案1】:

    只是为了添加上面 Arka Mukherjee 的答案,以获得我这样做的令牌:

    auth_data = { 'USERNAME':username , 'PASSWORD':password }
    provider_client=boto3.client('cognito-idp', region_name=region)
    resp = provider_client.admin_initiate_auth(UserPoolId=user_pool_id, AuthFlow='ADMIN_NO_SRP_AUTH', AuthParameters=auth_data, ClientId=client_id)
    token = resp['AuthenticationResult']['IdToken']
    

    这里我必须使用 Cognito 用户的用户名和密码,client_id 是我通过 Cognito 设置的应用程序客户端的应用程序客户端 ID,user_pool_id 是用户池 ID。

    请注意,我的应用客户端已选中/选中此选项:启用登录 API 以进行基于服务器的身份验证 (ADMIN_NO_SRP_AUTH),并且我创建了没有密钥的应用客户端(显然这对 Web 客户端尤其重要)。

    【讨论】:

      【解决方案2】:

      要传递 Cognito 用户池 JWT 令牌,您需要在 GetId API 调用中使用 Logins Map。在替换必要的占位符后,您可以尝试以下 Python 代码。

      response = client.get_id(
          AccountId='string',
          IdentityPoolId='string',
          Logins={
              'cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>': '<JWT ID Token>'
          }
      )
      

      如果您不提供登录映射,Amazon Cognito 会将身份验证事件视为未经身份验证,因此您将面临此错误。

      【讨论】:

      • 谢谢,但这引出了一个问题:我在哪里可以获得 JWT 令牌?有没有办法使用 boto 或 boto3 来获得这个?
      • 您在成功的用户池身份验证事件后获得 JWT 令牌。这可以使用 InitiateAuth 或 AdminInitiateAuth API 调用来实现。
      • 您可以参考this API。
      猜你喜欢
      • 2016-01-17
      • 2014-12-05
      • 2019-09-25
      • 1970-01-01
      • 2016-06-29
      • 2019-01-29
      • 2018-01-29
      • 2016-08-04
      • 2015-05-10
      相关资源
      最近更新 更多