Authorization Header
Authorization
Almost all APIs need to carry the "Authorization" HTTP request header parameter for identity authentication.
How to generate Authorization
- Get account_id and account_key from console dashboard,such as: account_id = "xp9mzzxttrrjheg8jtojwskqzz64zq3j" account_key = "h9yldjrzxaeiabtad0kb4ty5ivj7ehr1"
- Get current timestamp : "timestamp=1531476256"
- Generate a random nonce: "nonce=frxwel0nioxt92smrtn509majr5750lj"
- Connect account_id, timestamp, nonce into one string: "xp9mzzxttrrjheg8jtojwskqzz64zq3j1531476256frxwel0nioxt92smrtn509majr5750lj"
- Use account_key to do hamc-sha256 signature on joinstr, and get signature in hexadecimal encoding:"signature=8b753bc5b5cd1bc58b4bbee2f1f88f6cbfbe66839eb9c57a4b6b9056cc439902"
- 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
- Python
- Go
- Java
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
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"math/rand"
"strconv"
"strings"
"time"
)
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
var accountID = "647f5ed2ed8a********84e01556bb71"
var accountKey = "b09a7aafbfd********a9b530d0337bf"
func generateRandomID(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return strings.ToLower(string(b))
}
func HmacSha256Sign(in, secret string) (string, error) {
h := hmac.New(sha256.New, []byte(secret))
_, err := h.Write([]byte(in))
if err != nil {
return "", err
}
result := hex.EncodeToString(h.Sum(nil))
return result, nil
}
func makeAuthorization() string {
timestamp := strconv.FormatInt(time.Now().Unix(), 10)
rand.Seed(time.Now().UnixNano())
nonce := generateRandomID(32)
joinStr := strings.Join([]string{accountID, timestamp, nonce}, "")
signature, _ := HmacSha256Sign(joinStr, accountKey)
authorization := fmt.Sprintf("account_id=%s,nonce=%s,signature=%s,timestamp=%s", accountID, nonce, signature, timestamp)
return authorization
}
func main() {
authorization := makeAuthorization()
fmt.Println(authorization)
}
package demo;
import java.util.UUID;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import static com.utils.ByteFormat.bytesToHexString;
public class demo {
private static final String ACCOUNT_ID = "647f5ed2ed8a********84e01556bb71";
private static final String ACCOUNT_KEY = "b09a7aafbfd********a9b530d0337bf";
public static String generateRandomID() {
UUID randomUUID = UUID.randomUUID();
return randomUUID.toString().replaceAll("-", "");
}
public static final String bytesToHexString(byte[] bArray) {
StringBuffer sb = new StringBuffer(bArray.length);
for (int i = 0; i < bArray.length; ++i) {
String sTemp = Integer.toHexString(255 & bArray[i]);
if (sTemp.length() < 2) {
sb.append(0);
}
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}
public static String sha256_HMAC(String message, String secret) {
String hash = "";
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
hash = bytesToHexString(bytes);
} catch (Exception e) {
System.out.println("Error HmacSHA256 ===========" + e.getMessage());
}
return hash;
}
public static String makeAuthorization(){
String authorization = "";
String nonce = generateRandomID();
long timeNew = System.currentTimeMillis()/ 1000;
String timestamp = String.valueOf(timeNew);
String joinString = String.join("", ACCOUNT_ID, timestamp, nonce);
String signature = sha256_HMAC(joinString, ACCOUNT_KEY).toLowerCase();
authorization = String.format("account_id=%s,nonce=%s,signature=%s,timestamp=%s", ACCOUNT_ID, nonce, signature, timestamp);
return authorization;
}
public static void main(String[] args) {
String authorization = makeAuthorization();
System.out.println(authorization);
}
}