为API访问生成签名(Oauth 1.0)

2024-04-18 18:05:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用python和oauth 1.0访问API。我不知道如何生成oauth_签名。下面是我的代码到目前为止,希望有人能帮助。

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)

api开发人员建议我如何访问它:

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.


Tags: andthekeyimporttokenstringaccessconsumer