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

纵然是瞬间 提交于 2019-12-06 07:30:02

问题


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

Everything is fine until Step 4: Exchange authorization code for Access Token

I wrote the following python script to retrieve the code:

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.

I am 100% sure that the login credentials are fine, so it seems to be related to the way I make the request. It's also the first time that I am using "requests" in 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


回答1:


Change your body variable to a dict, i.e.,

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

No other changes are needed. Hope it helps.




回答2:


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. The problem is that the code generated in step 2 in the link can be only use ONCE. And this will get the same 401 error. This took me some time to figure it out. Hope this helps others.



来源:https://stackoverflow.com/questions/30817089/retrieve-access-token-for-yahoo-api-using-oauth-2-0-and-python-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!