使用POST请求,我的目标是从JSON响应中接收授权代码。然而,我得到的唯一响应是我连接的网页的HTML,而不是所需的JSON响应。
import requests
from base64 import b64encode
appAuth = b64encode(b"QT8txxxxxxxx:n76mxxxxxxxxx").decode("ascii")
headers = { 'Authorization' : 'Basic %s' % appAuth }
url = "http://demo.skubana.com?grant_type=authorization_code&redirect_uri=demo.skubana.com/appstore&code=LCqYHU&cid=Y29tcGFueUlkMTI0MDYw"
r = requests.post(url, headers=headers,json={})
print(r.status_code)
print(r.content)
在我看来,为Skubana提供的API文档严重不足。
您可能错过了以下部分:
- 添加请求路径:/oauth/token
公平地说,这并没有反映在他们的"示例URL"中:
示例Url:
https://blah.skubana.com?grant_type=authorization_code&redirect_uri=redirect.com/callback&code=ABCDE&cid=ABCD1234
当您更改URL以包含该路径时,我会收到401未经授权的响应:
>>> url = "http://demo.skubana.com/oauth/token?grant_type=authorization_code&redirect_uri=demo.skubana.com/appstore&code=LCqYHU&cid=Y29tcGFueUlkMTI0MDYw"
>>> r = requests.post(url, headers=headers)
>>> r.status_code
401
顺便提一下,这也涉及到从POST到GET的重定向。但我强烈怀疑有了正确的凭据(我没有(,你真的会得到你的代币。
当您发布到https://demo.skubana.com
时,会重定向,首先重定向到相同的URL以发出GET请求,其中包含:
Location: https://demo.skubana.com/?grant_type=authorization_code&redirect_uri=demo.skubana.com/appstore&code=LCqYHU&cid=Y29tcGFueUlkMTI0MDYw
然后转到您的仪表板:
Location: /work/dashboard
最后进入登录页面:
Location: https://demo.skubana.com/login
所有这些都记录在r.history
列表中:
>>> r.history
[<Response [302]>, <Response [302]>, <Response [302]>]
请注意,不必设置json={}
,只需使用:
r = requests.post(url, headers=headers)
请求库可以为您处理Base64编码,因为这只是基本身份验证方案的一部分,只需将YOUR_APP_KEY和YOUR_APP_SECRET值作为用户名和密码:
YOUR_APP_KEY = "QT8txxxxxxxx"
YOUR_APP_SECRET = "n76mxxxxxxxxx"
url = "http://demo.skubana.com/oauth/token"
parameters = {
"grant_type": "authorization_code",
"redirect_uri": "demo.skubana.com/appstore",
"code": "LCqYHU",
"cid": "Y29tcGFueUlkMTI0MDYw",
}
r = requests.post(url, params=parameters, auth=(YOUR_APP_KEY, YOUR_APP_SECRET))
最后,考虑到重定向和完全没有POST参数,我强烈怀疑GET请求也能正常工作:
r = requests.get(url, params=parameters, auth=(YOUR_APP_KEY, YOUR_APP_SECRET))
这只是绕过POST->GET重定向。
通常,OAuth2对这样一个令牌的请求会在post主体中发布参数,所以也要尝试:
r = requests.post(url, data=parameters, auth=(YOUR_APP_KEY, YOUR_APP_SECRET))
如果params=parameters
选项仍然不能获得您的代币。