Authentication Configuration

Last update:2024-08-20 18:14:06

The generation of authentication tokens requires user cooperation in development. After creating a new API in the console, you will see the key required for authentication in “API Endpoint - Authentication Configuration”. Copy the key, which is the encryption key used in the authentication algorithm. Develop according to the provided example code, and after completion, each API call by the user will be accompanied by a dynamic authentication token. After enabling key Pair Authentication, the correctness and validity of the authentication token in each request will be checked. Only tokens that are correct within the validity period can pass authentication.

The code example supports three development languages: Python, Java, and Shell. The complete code example is as follows:

Configuration:

1. Pending authentication API: http://your.domain/api
2. Signature Algorithm:HmacSHA256
3. Key:secret_key_str
4. Authentication:HEADER. 
Authentication Header key:X_Sam_Auth
 
Code Example:

1.python
 
import binascii
import hmac
import hashlib
import time
import requests
 
secret_key_str = "secret_key_str"
tmp_timestamp = str(int(time.time()))
tmp_binary = hmac.new(secret_key_str.encode("utf-8"), tmp_timestamp.encode("utf-8"), digestmod=hashlib.sha256).digest()
// Convert encrypted byte array to hexadecimal string
tmp_hex = binascii.hexlify(tmp_binary).decode("utf-8")
 
headers = {
    "X-Date": tmp_timestamp,
    "X_Sam_Auth": tmp_hex
}
url = "http://your.domain/api"
resp = requests.get(url, headers=headers)
 
2.java
 
import cn.hutool.core.util.HexUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
 
public static void main(String[] args) throws Exception{
    String key = "secret_key_str";
    String timestamp = String.valueOf(System.currentTimeMillis()/1000);
    Mac sha256 = Mac.getInstance("HmacSHA256");
    SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"),"HmacSHA256");
    sha256.init(secretKeySpec);
    // Convert encrypted byte array to hexadecimal string
    String hex = HexUtil.encodeHexStr(sha256.doFinal(timestamp.getBytes("UTF-8")));
 
    String url = "http://your.domain/api";
    HttpResponse response = HttpUtil.createGet(url).header("X-Date", timestamp)
            .header("X_Sam_Auth", hex).execute();
}
 
3.shell
 
#!/bin/bash
secret_key_str="secret_key_str"
current=`date "+%Y-%m-%d %H:%M:%S"`
tmp_timestamp=`date -d "$current" +%s`
tmp_hex=`echo -en "$tmp_timestamp" | openssl dgst -sha256 -hmac $secret_key_str -binary | hexdump -ve '/1 "%02x"'`
curl -i --url "http://your.domain/api" \
-X "GET" \
-H "X-Date: $tmp_timestamp" \
-H "X_Sam_Auth: $tmp_hex"
Is the content of this document helpful to you?
Yes
I have suggestion
Submitted successfully! Thank you very much for your feedback, we will continue to strive to do better!