【问题标题】:Transform Curl Oauth2 to Python Script将 Curl Oauth2 转换为 Python 脚本
【发布时间】:2020-06-10 06:13:21
【问题描述】:

以下 bash 脚本有效并返回一个令牌。

curl -X POST --user <id>:<key> 'https://<name>.auth.eu-west-1.amazoncognito.com/oauth2/token?grant_type=client_credentials' -H 'Content-Type: application/x-www-form-urlencoded'

我现在想通过 Python 脚本生成一个令牌。我目前正在努力使用 requests 库,但没有成功。下面生成响应 400(错误请求)。

import requests
parameters = {"user":"<id>:<key>", "Content-Type": "application/x-www-form-urlencoded"}
response = requests.get("https://<name>.auth.eu-west-1.amazoncognito.com/oauth2/token?grant_type=client_credentials", params=parameters)
print(response)

【问题讨论】:

    标签: python curl oauth-2.0 amazon-cognito access-token


    【解决方案1】:

    修正你对requests的使用:

    • 使用post() 而不是get()
    • 使用auth 对象来构造基本的身份验证标头。 (或在正文中发送凭据)
    • 删除内容类型标头; requests 将为您设置。
    • 从查询字符串中取出grant_type。这属于请求正文。

    虽然/oauth2/token 端点的文档说您需要为client_credentials 授予发送基本身份验证标头,但如果您在请求正文中发送客户端ID 和机密(没有身份验证标头),它也可以工作。

    因此,这些 python 示例都有效,并且本质上是等效的:

    请求正文中的凭据:

    import requests
    
    url = 'https://<COGNITO_DOMAIN>.auth.<REGION>.amazoncognito.com/oauth2/token'
    params = {
        "client_secret": "1ixxxxxxxxxxxxxxxxc2b",
        "grant_type": "client_credentials",
        "client_id": "7xxxxxxxxxxxxxxxt"
    }
    response = requests.post(url, data=params)
    
    print(response)
    print(response.text)
    

    基本身份验证标头中的凭据:

    import requests
    
    url = 'https://<COGNITO_DOMAIN>.auth.<REGION>.amazoncognito.com/oauth2/token'
    params = {
        "grant_type": "client_credentials"
    }
    auth = ('7xxxxxxxxxxt', '1ixxxxxxxxxxxxxxxc2b')
    r = requests.post(url, data=params, auth=auth)
    
    print(r)
    print(r.text)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-01
      • 2016-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      • 2018-05-14
      • 1970-01-01
      相关资源
      最近更新 更多