简体   繁体   English

使用OAuth 2.0和Python请求检索Yahoo API的访问令牌

[英]Retrieve access token for Yahoo API using OAuth 2.0 and Python requests

I am trying to retrieve the access token for the Yahoo API, using the explicit grant flow as described in this document: https://developer.yahoo.com/oauth2/guide/flows_authcode 我正在尝试使用本文档中描述的显式授权流程来检索Yahoo API的访问令牌: https//developer.yahoo.com/oauth2/guide/flows_authcode

Everything is fine until Step 4: Exchange authorization code for Access Token 一切都很好,直到第4步:交换访问令牌的授权码

I wrote the following python script to retrieve the code: 我编写了以下python脚本来检索代码:

import urllib2
import requests
import json



url = 'https://api.login.yahoo.com/oauth2/get_token'
body = "grant_type=authorization_code&redirect_uri=oob&code=************"
headers = {
'Authorization': 'Basic **************', 
'Content-Type': 'application/json'
}

r = requests.post(url, data=body, headers=headers)
print r

Note: I replaced sensitive data with "****" 注意:我用“****”替换了敏感数据

Now, when I execute the script, I only get the "401" error message. 现在,当我执行脚本时,我只收到“401”错误消息。

I am 100% sure that the login credentials are fine, so it seems to be related to the way I make the request. 我100%确定登录凭据是好的,所以它似乎与我提出请求的方式有关。 It's also the first time that I am using "requests" in python. 这也是我第一次在python中使用“请求”。

Would be great, if you could give me some feedback on the code, and if I am passing the header and body information correctly. 如果你能给我一些关于代码的反馈,以及我是否正确传递了标题和正文信息,那就太棒了。 I am especially unsure about the passing of the body. 我特别不确定身体的流逝。 The documentation only states the following: 该文档仅说明以下内容:

Sample Request Body: grant_type=authorization_code&redirect_uri=https%3A%2F%2Fwww.example.com&code=abcdef 样本请求正文:grant_type = authorization_code&redirect_uri = https%3A%2F%2Fwww.example.com&code = abcdef

Change your body variable to a dict, ie, 将你的身体变量改为dict,即

body = {
    'grant_type': 'authorization_code',
    'redirect_uri': 'oob',
    'code': '************',
}

No other changes are needed. 无需其他更改。 Hope it helps. 希望能帮助到你。

Tough the problem already solved. 这个问题已经解决了。 But may be other user can still get the same 401 error even if they use correct dict as me. 但即使他们使用正确的字典作为我,其他用户仍然可以得到相同的401错误。 The problem is that the code generated in step 2 in the link can be only use ONCE. 问题是链接中步骤2中生成的代码只能使用ONCE。 And this will get the same 401 error. 这将得到相同的401错误。 This took me some time to figure it out. 这花了我一些时间才弄明白。 Hope this helps others. 希望这有助于其他人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM