Skip to main content

Authorization Header

Authorization

Almost all APIs need to carry the "Authorization" HTTP request header parameter for identity authentication.

How to generate Authorization

  1. Get account_id and account_key from console dashboard,such as: account_id = "xp9mzzxttrrjheg8jtojwskqzz64zq3j" account_key = "h9yldjrzxaeiabtad0kb4ty5ivj7ehr1"
  2. Get current timestamp : "timestamp=1531476256"
  3. Generate a random nonce: "nonce=frxwel0nioxt92smrtn509majr5750lj"
  4. Connect account_id, timestamp, nonce into one string: "xp9mzzxttrrjheg8jtojwskqzz64zq3j1531476256frxwel0nioxt92smrtn509majr5750lj"
  5. Use account_key to do hamc-sha256 signature on joinstr, and get signature in hexadecimal encoding:"signature=8b753bc5b5cd1bc58b4bbee2f1f88f6cbfbe66839eb9c57a4b6b9056cc439902"
  6. Join account_id, nonce, signature, timestamp as schema "key=value" by ",", then you will get the final Authorization string: account_id=xp9mzzxttrrjheg8jtojwskqzz64zq3j,nonce=ui8ghc9nhz4rosqnp8f2ey2fbeb1smog,signature=8b753bc5b5cd1bc58b4bbee2f1f88f6cbfbe66839eb9c57a4b6b9056cc439902,timestamp=1664161826

Sample Code

import hmac
import time
import random
import hashlib

account_id = '647f5ed2ed8a********84e01556bb71'
account_key = 'b09a7aafbfd********a9b530d0337bf'

def generate_rand_id(length=0):
"""
generate random id
:return:
"""
string = list(
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
res = ''
if not length:
ti = int(time.time())
random.shuffle(string)
sstr = ''.join(string)
rand = str(random.randint(0, 99999))
res = ''.join([str(ti), sstr, rand])
res = md5(res.encode()).hexdigest()
else:
for i in range(length):
res += string[random.randint(0, 61)]
return res.lower()

def _gen_encryptstring():
timestamp = str(int(time.time()))
nonce = generate_rand_id(32)
join_str = "".join((account_id, timestamp, nonce))
secret = bytes(account_key, encoding="utf-8")
message = bytes(join_str, encoding="utf-8")
signature = hmac.new(secret, message, digestmod=hashlib.sha256).hexdigest()
authorization = "account_id=%s,nonce=%s,signature=%s,timestamp=%s" % (account_id, nonce, signature, timestamp)
return authorization