【发布时间】:2016-01-26 12:19:16
【问题描述】:
我正在尝试使用 python 请求库通过 API 授权 bitly 应用程序。
我使用http://hottr.tk/ [NSFW] 作为我的回调网址。它是在位设置中设置的。
from lxml import html
from urllib import parse
import requests
# BASIC INITIALIZATION
username = 'username@fixme.org'
password = 'fixmetoo'
client_id = '18c1065bb7e3cfea7fa80d2c30ee974c6a9c4dba'
# CREATE REQUESTS SESSION
r = requests.session()
# LOGIN TO BITLY
response = r.get("https://bitly.com/a/sign_in")
s = html.fromstring(response.text)
_xsrf = s.xpath("//input[@name='_xsrf']")[0].value
r.headers = {
'X-Requested-With': 'XMLHttpRequest',
'X-XSRFToken': _xsrf,
'User-Agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
}
payload = {
'username': username,
'password': password,
'rd': '/',
'_xsrf': _xsrf,
'verificaton': 'true',
}
cookie = requests.utils.dict_from_cookiejar(r.cookies)
response = r.post("https://bitly.com/a/sign_in", headers=r.headers, data=payload, cookies=cookie)
# GET to REQUEST AUTHORIZE ENDPOINT
response = r.get("https://bitly.com/oauth/authorize?client_id=" + client_id + "&redirect_uri=" + parse.quote_plus('http://hottr.tk/'))
# POST to REQUEST AUTHORIZE ENDPOINT
r.headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'es',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
# 'Content-Length': '147',
'Content-Type': 'application/x-www-form-urlencoded',
'Host': 'bitly.com',
'Origin': 'https://bitly.com',
'Referer': 'https://bitly.com/oauth/authorize?client_id=" + client_id + "&redirect_uri=http://hottr.tk/',
'User-Agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
}
payload = {
'_xsrf': _xsrf,
'redirect_uri': parse.quote_plus('http://hottr.tk/'),
'client_id': client_id,
'state': '',
'action': 'Allow',
}
cookie = requests.utils.dict_from_cookiejar(r.cookies)
response = r.post("https://bitly.com/oauth/authorize", headers=r.headers, data=payload, cookies=cookie)
print(response.headers)
print(response.url)
此时,最后一个 POST 请求应该授权应用程序并返回类似 http://hottr.tk/?code=my_code_to_exchange_for_oauth_token 的 URL,但它只返回 response.url 这个 https://bitly.com/ 并且它没有 response.headers.location 变量,即 var应该包含带有code 参数的重定向网址
状态码都是200...
有人知道它为什么返回https://bitly.com 而不是我的重定向网址吗? :$
【问题讨论】:
标签: python api oauth python-requests