当我设置回调URL时,Twitter请求API返回总是401未授权

时间:2014-05-01 13:10:49

标签: api python-2.7 twitter

我想使用纯python代码检索access_tokenaccess_token_secrete

当我使用带有“oob”的回调网址时它正常工作 但我想设置一个像http://127.0.0.1/这样的网址,它是动态的。

我引用了很多堆栈溢出链接,但我的问题没有解决方案。

我还使用http://127.0.0.1/

将回拨网址设置为https://apps.twitter.com/app/

我的代码是:

from urllib2 import urlopen, Request, HTTPError, quote
from hashlib import sha1
import base64
import json
import random
import hmac
import time
import lxml.html
import urllib

#Server Links
REQUEST_URL = "https://api.twitter.com/oauth/request_token";
AUTHORIZE_URL = "https://api.twitter.com/oauth/authorize";
ACCESS_URL = "https://api.twitter.com/oauth/access_token";

#Consumer keys
API_key = "xxxxx"
API_secret = "xxxxxxxxxx"

# Build content header for POST to return request tokens
HEADER_TITLE = "Authorization"

oauth_callback_url = "http://127.0.0.1/"
#Consumer key
HEADER = 'OAuth oauth_callback="' + quote(oauth_callback_url,'') + '", oauth_consumer_key="' + API_key + '", '

#Nonce
HEADER += 'oauth_nonce="'
NONCE = ""
for i in range(32):
    NONCE += chr(random.randint(97, 122))
HEADER += NONCE
HEADER += '", '

#Timestamp
TIMESTAMP = str(int(time.time()))

#Signature
HEADER += 'oauth_signature="'
PARAMETER_STRING = "oauth_callback=" + oauth_callback_url + "&oauth_consumer_key=" + API_key + "&oauth_nonce=" + NONCE + "&oauth_signature_method=HMAC-SHA1&oauth_timestamp=" + TIMESTAMP + "&oauth_version=1.0"
BASE_STRING = 'POST&' + quote(REQUEST_URL, '') + '&' + quote(PARAMETER_STRING, '')
SIGNING_KEY = quote(API_secret, '') + '&'
print("DEBUG : SIGNING KEY " + SIGNING_KEY + " BASE STRING " + BASE_STRING + "\n")
HEADER += quote(base64.standard_b64encode(hmac.new(SIGNING_KEY.encode(), BASE_STRING.encode(), sha1).digest()).decode('ascii'))
HEADER += '", '

#Signature Method
HEADER += 'oauth_signature_method="HMAC-SHA1", '

#Timestamp
HEADER += 'oauth_timestamp="' + TIMESTAMP + '", '

#Version
HEADER += 'oauth_version="1.0"'

print(HEADER_TITLE + ":\n" + HEADER)

HTTP_REQUEST = Request(REQUEST_URL)
HTTP_REQUEST.add_header(HEADER_TITLE, HEADER)
request_token_response = urlopen(HTTP_REQUEST, '').read()
request_token_response = dict(item.split("=") for item in request_token_response.split("&"))
print request_token_response

request_token = request_token_response['oauth_token']
request_token_secret = request_token_response['oauth_token_secret']


authorize_token_response = urlopen(AUTHORIZE_URL + "?oauth_token=" + request_token).read()
print "authenication---------------",authorize_token_response

我的问题在哪里?

1 个答案:

答案 0 :(得分:-1)

更改我的Twitter应用程序的设置。对于回拨网址,

  • 您可以从https://apps.twitter.com/
  • 更改此设置
  • 然后选择您的应用
  • 转到设置标签
  • 设置回调网址 enter image description here
  • 必须勾选标记,以便将回拨网址添加到您的请求标题中。

使用此我可以解决我的问题。