Python request error - python

I am trying to make a request using headers I have URL encoded. When I run, i get error 500 for some reason. If the code was working we should get back an oauth_token and oauth_token_secret.
following these instructions : http://developer.trademe.co.nz/api-overview/authentication/example-oauth-flow/
import hashlib
import hmac
import base64
import time
from rauth.service import OAuth1Service
import oauth
import rauth
import requests
import oauth2 as oauth1
from urllib.parse import parse_qs
import urllib
nonce = oauth1.generate_nonce()
time = int(time.time())
consumer_key = "5C82CC6BC7C6472154FBC9CAB24A29A2"
New_base_string ="POST&https%3A%2F%2Fsecure.tmsandbox.co.nz%2FOauth%2FRequestToken&oauth_callback%3Dhttp%253A%252F%252Fwww.website-tm-access.co.nz%252Ftrademe-callback%26oauth_consumer_key%" + str(consumer_key) +"3DC74CD73FDBE37D29BDD21BAB54BC70E422%26oauth_nonce%3" + str(nonce) + "%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3" + str(time) + "%26oauth_version%3D1.0%26scope%3DMyTradeMeRead%252CMyTradeMeWrite"
New_base_string= New_base_string.encode()
KEY = b"5C82CC6BC7C6472154FBC9CAB24A29A2&"
digest = hmac.new(KEY, New_base_string, hashlib.sha1).digest()
signature = (base64.b64encode(digest))
print(base64.b64encode(digest))
url = 'https://secure.tmsandbox.co.nz/Oauth/RequestToken?scope=MyTradeMeRead,MyTradeMeWrite '
headers = {'oauth_callback': "http://www.website-tm-access.co.nz%2Ftrademe-callback",
'oauth_consumer_key' : "C74CD73FDBE37D29BDD21BAB54BC70E422" ,
'oauth_version': "1.0",
'oauth_timestamp': time, #int(time.time()),
'oauth_nonce' : nonce,
'oauth_signature_method' : "HMAC-SHA1",
'oauth_signature' : signature
}
authorization = '5C82CC6BC7C6472154FBC9CAB24A29A2 ' + ', '.join([key + '="' + urllib.parse.quote_plus(str(value)) + '"' for key, value in headers.items()])
http_headers = {'Authorization': authorization}
print(authorization)
r = requests.get(url, headers=http_headers)
*ERROR: * Error 500

Related

How can I convert the digital signature from HMAC-SHA1 to HMAC-SHA256 for a Netsuite API?

The working SHA-1 code is as so.
import oauth2 as oauth
import requests
import hmac
import hashlib
from base64 import b64encode #To encode binary data into Base64
import binascii
import requests
import random
import time
import urllib.parse
url = apiURL
token = oauth.Token(key='x')
consumer = oauth.Consumer(key='x')
http_method = 'POST'
realm="xxx"
params = {
'oauth_version': '1.0',
'oauth_nonce': oauth.generate_nonce(),
'oauth_timestamp': str(int(time.time())),
'oauth_token': token.key,
'oauth_consumer_key': consumer.key
}
req = oauth.Request(method=http_method, url=url, parameters=params)
signature_method = oauth.SignatureMethod_HMAC_SHA1()
req.sign_request(signature_method, consumer, token)
header = req.to_header(realm)
print(header['Authorization'])
headery = header['Authorization'].encode('ascii', 'ignore')
headerx = {"Authorization": headery, "Content-Type": "application/json"}
#print(headerx)
payload = {"operation": "moveFile", "id": "1450"}
conn = requests.post(url, data=netSuiteData, headers=headerx)
# print("\n\nResult: " + conn.text)
# print("\n\n\n")
# print(conn.headers)
After researching the issue I found a similar problem from a post over a year old. I implemented the solution suggested as so:
import oauth2 as oauth
import requests
import hmac
import hashlib
from base64 import b64encode #To encode binary data into Base64
import binascii
import requests
import random
import time
import urllib.parse
url = apiURL
method = 'POST'
access_token = "x"
token_secret = "x"
oauth_consumer_key = "x"
consumer_secret = "x"
oauth_signature_method = "HMAC-SHA256"
oauth_version = "1.0"
oauth_nonce = ''.join(random.choices("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", k=11))
oauth_timestamp = str(int(time.time()))
account = 'x'
body = netSuiteData
def create_parameter_string(oauth_consumer_key,oauth_nonce,oauth_signature_method,oauth_timestamp,oauth_version, token_id):
parameter_string = ''
parameter_string = parameter_string + 'oauth_consumer_key=' + oauth_consumer_key
parameter_string = parameter_string + '&oauth_nonce=' + oauth_nonce
parameter_string = parameter_string + '&oauth_signature_method=' + oauth_signature_method
parameter_string = parameter_string + '&oauth_timestamp=' + oauth_timestamp
parameter_string = parameter_string + '&oauth_token=' + token_id
parameter_string = parameter_string + '&oauth_version=' + oauth_version
return parameter_string
parameter_string = create_parameter_string(oauth_consumer_key,oauth_nonce,oauth_signature_method,oauth_timestamp,oauth_version,access_token)
encoded_parameter_string = urllib.parse.quote(parameter_string, safe='')
encoded_base_string = method + '&' + urllib.parse.quote(url, safe='')
encoded_base_string = encoded_base_string + '&' + encoded_parameter_string
signing_key = consumer_secret + '&' + token_secret
def create_signature(secret_key, signature_base_string):
encoded_string = signature_base_string.encode()
encoded_key = secret_key.encode()
temp = hmac.new(encoded_key, encoded_string, hashlib.sha256).hexdigest()
byte_array = b64encode(binascii.unhexlify(temp))
return byte_array.decode()
oauth_signature = create_signature(signing_key, encoded_base_string)
encoded_oauth_signature = urllib.parse.quote(oauth_signature, safe='')
print("param" + parameter_string )
headers = {
'Content-Type':'application/x-www-form-urlencoded',
'Authorization':'OAuth realm="{0}",oauth_consumer_key="{1}",oauth_token="{2}",oauth_signature_method="{3}",oauth_timestamp="{4}",oauth_nonce="{5}",oauth_version="{6}",oauth_signature="{7}"'.format(
str(account),oauth_consumer_key,access_token,oauth_signature_method, oauth_timestamp ,oauth_nonce,oauth_version ,encoded_oauth_signature)
}
print("headers***************")
print(headers)
response = requests.post(url, data=body, headers=headers)
print(response.text)
The first block of code works just fine, however when testing the new block of code (when running the script which needs signatures generated) - the console is telling me access was denied, and the authentication failed.

Coinbase API Python request syntax question

I am having trouble with the code in that every time I go to run it, it receive an error as follows:
File "/Users/richard/Desktop/Python/gdaxauth.py", line 27
request.headers.update({ ^
SyntaxError: invalid syntax
So it seems to relate to something in the request.headers.update section. I have tried researching this but have hit a total brick wall. Can anyone advise as to what the correct syntax should be? I am using Python 3.7.
import json
import hmac
import hashlib
import time
import requests
import base64
import urllib
from requests.auth import AuthBase
# Tracking execution time
start = time.time()
# Create custom authentication for Exchange
class CoinbaseExchangeAuth(AuthBase):
def __init__(self, api_key, secret_key, passphrase):
self.api_key = api_key
self.secret_key = secret_key
self.passphrase = passphrase
def __call__(self, request):
timestamp = str(time.time())
message = timestamp + request.method + request.path_url + (request.body or '')
hmac_key = base64.b64decode(self.secret_key)
signature = hmac.new(hmac_key, message.encode('utf-8'), hashlib.sha256)
signature_b64 = base64.b64encode(signature.digest().rstrip('\n')
request.headers.update({
'CB-ACCESS-SIGN': signature_b64,
'CB-ACCESS-TIMESTAMP': timestamp,
'CB-ACCESS-KEY': self.api_key,
'CB-ACCESS-PASSPHRASE': self.passphrase,
'Content-type': 'application/json'
})
return request
# Credentials - ADD YOUR API KEY CREDS IN THIS SECTION
API_KEY = "xxxxxxxxx"
SECRET_KEY = "xxxxxxxxxx"
API_PASSPHRASE = "xxxxxxxxxx"
# Get accounts
api_url = 'https://api.gdax.com/' #'https://api.pro.coinbase.com'
auth = CoinbaseExchangeAuth(API_KEY,SECRET_KEY,API_PASSPHRASE)
r = requests.get(api_url + 'accounts', auth=auth)
# Output account data and code execution time
print(json.dumps(r.json(),indent=4))

How do I generate the rest authorization token for cosmos db in python?

I'm having trouble generating the authorization token for cosmos db for a simple get databases request. Here is my python code:
import requests
import hmac
import hashlib
import base64
from datetime import datetime
key = 'AG . . .EZPcZBKz7gvrKiXKsuaPA=='
now = datetime.utcnow().strftime('%a, %d %b %Y %H:%M:00 GMT')
payload = ('get\ndbs\n\n' + now + '\n\n').lower()
signature = base64.b64encode(hmac.new(key, msg = payload, digestmod = hashlib.sha256).digest()).decode()
url = 'https://myacct.documents.azure.com/dbs'
headers = {
'Authorization': "type=master&ver=1.0&sig=" + signature,
"x-ms-date": now,
"x-ms-version": "2017-02-22"
}
res = requests.get(url, headers = headers)
print res.content
Which produces this error:
{"code":"Unauthorized","message":"The input authorization token can't serve the request. Please check that the expected payload is built as per the protocol, and check the key being used. Server used the following payload to sign: 'get\ndbs\n\nsun, 08 apr 2018 02:39:00 gmt\n\n'\r\nActivityId: 5abe59d8-f44e-42c1-9380-5cf4e63425ec, Microsoft.Azure.Documents.Common/1.21.0.0"}
Greg. Per my observe, the miss of your code is url encode. You could find the sample code here.
Please refer to my code which was made a slight adjustment to your code.
import requests
import hmac
import hashlib
import base64
from datetime import datetime
import urllib
key = '***'
now = datetime.utcnow().strftime('%a, %d %b %Y %H:%M:00 GMT')
print now
payload = ('get\ndbs\n\n' + now + '\n\n').lower()
payload = bytes(payload).encode('utf-8')
key = base64.b64decode(key.encode('utf-8'))
signature = base64.b64encode(hmac.new(key, msg = payload, digestmod = hashlib.sha256).digest()).decode()
print signature
authStr = urllib.quote('type=master&ver=1.0&sig={}'.format(signature))
print authStr
headers = {
'Authorization': authStr,
"x-ms-date": now,
"x-ms-version": "2017-02-22"
}
url = 'https://***.documents.azure.com/dbs'
res = requests.get(url, headers = headers)
print res.content
Execute result:
Hope it helps you.

Python Script Using Amazon Product API Not Functioning

import re
import time
import urllib
import base64
import hmac
import hashlib
import requests
import xml.etree.ElementTree as ET
from xml.etree import ElementTree as et
import codecs
import xml.etree.cElementTree as EF
from datetime import date
import bitly_api
def aws_signed_request(region, params, public_key, private_key, associate_tag=None, version='2011-08-01'):
# some paramters
method = 'GET'
host = 'webservices.amazon.' + region
uri = '/onca/xml'
# additional parameters
params['Service'] = 'AWSECommerceService'
params['AWSAccessKeyId'] = public_key
params['Timestamp'] = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
params['Version'] = version
if associate_tag:
params['AssociateTag'] = associate_tag
# create the canonicalized query
canonicalized_query = [urllib.quote(param).replace('%7E', '~') + '=' + urllib.quote(params[param]).replace('%7E', '~')
for param in sorted(params.keys())]
canonicalized_query = '&'.join(canonicalized_query)
# create the string to sign
string_to_sign = method + '\n' + host + '\n' + uri + '\n' + canonicalized_query
#print string_to_sign
# calculate HMAC with SHA256 and base64-encoding
signature = base64.b64encode(hmac.new(key=private_key, msg=string_to_sign, digestmod=hashlib.sha256).digest())
# encode the signature for the request
signature = urllib.quote(signature).replace('%7E', '~')
print 'http://' + host + uri + '?' + canonicalized_query + '&Signature=' + signature
return 'http://' + host + uri + '?' + canonicalized_query + '&Signature=' + signature
This is part of my code that used to be functional. It would get the best selling Amazon items in several categories. However, this script is not longer functioning. Does anyone notice anything wrong?
Fixed, my public and private key was expired

bitfinex api v2 error, invalid key

I am trying to make a basic authenticated api call to their new v2 api and getting an invalid api key error returned.
I reissued the api key just to verify, same error.
from time import time
import urllib.request
import urllib.parse
import hashlib
import hmac
APIkey = b'myapikeyyouarenotsupposedtosee'
secret = b'myceeeeecretkeyyyy'
url = 'https://api.bitfinex.com/v2/auth/r/wallets'
payload = {
#'request':'/auth/r/wallets',
'nonce': int(time() * 1000),
}
paybytes = urllib.parse.urlencode(payload).encode('utf8')
print(paybytes)
sign = hmac.new(secret, paybytes, hashlib.sha512).hexdigest()
print(sign)
headers = {
'Key': APIkey,
'Sign': sign
}
req = urllib.request.Request(url, headers=headers, data=paybytes)
with urllib.request.urlopen(req) as response:
the_page = response.read()
print(the_page)
How do I make an authenticated api call to the new v2 API for bitfinex?
Your headers are wrong. I was also trying to do this and tried using the example code from the bitfinex v2 api docs, however their example contained a bug in that they needed to encode the strings into UTF-8 byte arrays first. So I've fixed it and posting the entire example below.
#
# Example Bitfinex API v2 Auth Python Code
#
import requests # pip install requests
import json
import base64
import hashlib
import hmac
import os
import time #for nonce
class BitfinexClient(object):
BASE_URL = "https://api.bitfinex.com/"
KEY = "API_KEY_HERE"
SECRET = "API_SECRET_HERE"
def _nonce(self):
# Returns a nonce
# Used in authentication
return str(int(round(time.time() * 10000)))
def _headers(self, path, nonce, body):
secbytes = self.SECRET.encode(encoding='UTF-8')
signature = "/api/" + path + nonce + body
sigbytes = signature.encode(encoding='UTF-8')
h = hmac.new(secbytes, sigbytes, hashlib.sha384)
hexstring = h.hexdigest()
return {
"bfx-nonce": nonce,
"bfx-apikey": self.KEY,
"bfx-signature": hexstring,
"content-type": "application/json"
}
def req(self, path, params = {}):
nonce = self._nonce()
body = params
rawBody = json.dumps(body)
headers = self._headers(path, nonce, rawBody)
url = self.BASE_URL + path
resp = requests.post(url, headers=headers, data=rawBody, verify=True)
return resp
def active_orders(self):
# Fetch active orders
response = self.req("v2/auth/r/orders")
if response.status_code == 200:
return response.json()
else:
print('error, status_code = ', response.status_code)
return ''
# fetch all your orders and print out
client = BitfinexClient()
result = client.active_orders()
print(result)
Why not use one of the open source api clients out there ? and you can compare to your work .
https://github.com/scottjbarr/bitfinex
https://github.com/tuberculo/bitfinex

Categories