4

I am trying to access an API using python and oauth 1.0. I cant get how to generate a oauth_signature. Below is my code so far, hope someone can help.

import oauth2 as oauth
import urllib.parse
import time
from random import getrandbits


api_key = 'xxxxxxxxxxxxxxxxxxx'
CONSUMER_KEY = 'xxxxxxxxxxxxxxxxx'
CONSUMER_SECRET = 'xxxxxxxxxxxxxxxxx'
access_key = 'xxxxxxxxxxxxxxxxx'
access_secret_key = 'xxxxxxxxxxxxxxxxxxx'

consumer = oauth.Consumer(CONSUMER_KEY, CONSUMER_SECRET)
token = oauth.Token(access_key, access_secret_key)

client = oauth.Client(consumer, token)

nonce = str(getrandbits(64))
print(nonce)

url = 'https://secure.tmsandbox.co.nz/Oauth/Authorize?oauth_token='

params = {'oauth_version': "1.0", 
          'oauth_nonce': oauth.generate_nonce(), 
          'oauth_timestamp': int(time.time()),
          'oauth_consumer_key': CONSUMER_KEY,
          'oauth_token': access_key,
          'oauth_nonce' : nonce, 
          'oauth_consumer_key': consumer.key,
          'oauth_signature': 'el078a5AXGi43FBDyfg5yWY',
          }

req = oauth.Request(method="POST", url='https://secure.tmsandbox.co.nz/Oauth/RequestToken?', parameters=params)



# Sign the request.
signature_method = oauth.SignatureMethod_HMAC_SHA1()
req.sign_request(signature_method, consumer, token)

How api developers suggest I access it:

The oauth_signature is a little harder to come up with and is where most people trip up. To generate a signature you start with a base string that begins with the HTTP method and the URL encoded address you are calling (without the query string). As we are getting a request token, this will be a POST request to https://secure.trademe.co.nz/Oauth/RequestToken?scope=MyTradeMeRead,MyTradeMeWrite (note that in this example the scope parameter is used to request read/write access). This is the start of our base string:

POST&https%3A%2F%2Fsecure.trademe.co.nz%2FOauth%2FRequestToken

Notice that we separated these with an ampersand (&). Sort all the parameter keys (oauth_nonce, etc) and any query string parameters alphabetically (excluding the oauth_signature as that is what we are generating) and append them in a separate string, [name]=[value] separating each with an ampersand. URL encode this and append it to the end of the base string, preceded by an ampersand.

musss
  • 125
  • 1
  • 4
  • 16

1 Answers1

1

Check this answer .It explains how to use HMAC - SHA1 signature method and access a website using OAuth.

Community
  • 1
  • 1
mvresh
  • 21
  • 2
  • found an interesting method in that thread, might look into this instead of encrypting : [link](http://stackoverflow.com/a/32060758/5932561) – musss Feb 20 '16 at 10:23