Always getting 401 Unathorized for OpenAuth by python 2.7


#1

Help me somewhere please. I can’t use Twitter Authorization.

My next python code, always returns 401:

def hmac_sha1(raw): key = '%s&' % TWITTER_CONSUMER_SECRET hashed = hmac.new(key, raw, sha1) return binascii.b2a_base64(hashed.digest()).rstrip('\n')

def connect(request):

twitter_request = urllib2.Request(url='https://api.twitter.com/oauth/request_token')
callback_uri = urllib.quote('http://' + request.META.get('HTTP_HOST')
                            + reverse('social_analyze', args=('twitter',))) # just getting callback_uri it's ok

ts = int(round(time.time())) # Maybe this string is blame?
nonce = base64.standard_b64encode('n' +
                                  (''.join(
                                      random.choice(string.ascii_lowercase + string.digits) for _ in range(16))))

sig_string = 'POST&' + urllib.quote('https://api.twitter.com/oauth/request_token') + '&'
sig_string += urllib.quote('oauth_callback=%s' % callback_uri)
sig_string += urllib.quote('&oauth_consumer_key=%s' % TWITTER_CONSUMER_KEY)
sig_string += urllib.quote('&oauth_nonce=%s' % nonce)
sig_string += urllib.quote('&oauth_signature_method=HMAC-SHA1')
sig_string += urllib.quote('&oauth_timestamp=%s' % ts)
sig_string += urllib.quote('&oauth_version=1.0')
sig = urllib.quote(hmac_sha1(sig_string))

first_call_header = 'OAuth oauth_callback="%s", oauth_consumer_key="%s", ' \
                    'oauth_nonce="%s", oauth_signature_method="HMAC-SHA1", oauth_timestamp="%s", ' \
                    'oauth_signature="%s", oauth_version="1.0"'
first_call_header = first_call_header % (callback_uri, TWITTER_CONSUMER_KEY, nonce, ts, sig)

twitter_request.add_header('Authorization', first_call_header)
twitter_request.get_method = lambda: 'POST'
twitter_response = urllib2.urlopen(twitter_request).read()

“TWITTER_CONSUMER_SECRET” is “Application settings -> API Secret”, am i right?
And “Application settings -> API key” is TWITTER_CONSUMER_KEY respectively


#2

problem solved: https://requests-oauthlib.readthedocs.org/en/latest/oauth1_workflow.html