【问题标题】:How to take take access tokens from oauth2如何从 oauth2 获取访问令牌
【发布时间】:2021-11-10 17:50:39
【问题描述】:

我在使用 python 从 oauth2 平台获取访问令牌时遇到问题。

目前,这就是我在发帖请求中使用的内容:

def token(self):
        client_id=ID_DO_CLIENTE
        client_secret=SECRET_TOKEN
        grant_type='client_credentials'

        response = requests.post("https://oauth2.googleapis.com/token",
                                auth=(client_id, client_secret),
                                 data={'grant_type':grant_type,'client_id':client_id,'client_secret':client_secret})
        print(response.text)

此特定代码返回以下错误:

{
  "error": "unsupported_grant_type",
  "error_description": "Invalid grant_type: "
}

但我认为问题不在于 grant_type,因为我已经尝试了我在网上找到的所有方法来解决这个问题。

无论如何,如果缺少任何信息,请告诉我。请帮忙!

【问题讨论】:

标签: python oauth-2.0 python-requests google-oauth refresh-token


【解决方案1】:

这是一个示例代码供参考:

data = {'grant_type': 'client_credentials'}
  requests.post(token_url, 
    
      data=data,
      auth=(client_id, client_secret))

在提供的示例代码中,数据部分发送不正确,即:

data={'grant_type':grant_type,'client_id':client_id,'client_secret':client_secret}

我觉得应该是这样的:

data={'grant_type':grant_type}

添加我正在测试的示例代码以验证令牌生成逻辑:

client_id = '<value>'
client_secret = '<value>'
# This is optional
scope = '<uri>'

#Token generation step
#If scope is not defined above then remove it from this call
data = {'grant_type': 'client_credentials','scope': scope}

access_token_response = requests.post(token_url, data=data, verify=False, allow_redirects=False, auth=(client_id, client_secret))

print (access_token_response.headers)
print (access_token_response.text)

tokens = json.loads(access_token_response.text)

print ("access token: " + tokens['access_token'])

【讨论】:

  • 它没有帮助,不幸的是:(但还是谢谢你
  • 刚刚添加了一个示例代码以供参考。
  • 我完全尝试了您的代码并得到了 302 响应,但响应中没有任何内容是实际令牌。我将编辑我的答案以发布一般的回复文本和正文
  • 你搞定了吗?
【解决方案2】:

有效的请求还需要这些标头才能以正确的格式发送数据 - 我怀疑默认情况下会发送 JSON,从而导致请求格式错误:

Content-Type: application/x-www-form-url-encoded
Authorization: Basic [base 64 encoded client id and secret]

技术

旨在首先使用 curl 工具获取令牌,以确保设置正确 - 如this article

还旨在通过HTTP proxy tool 跟踪请求,以确保正确发送电报消息。

这些技术将使您在使用 OAuth 时更有效率。

代码

我进行了搜索,this answer 似乎使用了正确的代码,尽管您可以像这样发送 Authorization 标头:

auth=HTTPBasicAuth('user', 'pass')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2019-03-13
    • 2015-07-27
    • 2015-02-11
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多