1. 获取token
需要登录上位机平台(“后台管理”->“系统设置”->“运维系统”->“安全设置”)查看Access Key ID和Access Key Secret
- 接口功能描述:获取token;
 - 接口路径:[GET]http://云服务IP:9191/ks/proxy/user/token;
 - 请求参数说明;
 
| 参数名称 | 数据类型 | 是否必须 | 说明 | 
|---|---|---|---|
| signature | String | 是 | 签名,生成方式见生成signature | 
| ak | String | 是 | Access Key ID | 
| timestamp | Int | 是 | 时间戳秒数,可通过获取系统时间戳接口获取,如1722995536 | 
| nonce | String | 是 | UUID,长度不超过64,生成签名和验签需使用相同nonce | 
- 请求示例;
 
| 项目 | 详情 | 
|---|---|
| 请求格式 | Query String | 
| signature | 935816eb7b881e37a1761856…… | 
| ak | 66b1dc29ca6e4e……. | 
| timestamp | 1722995536 | 
| nonce | skaoqpcnskjnklamk | 
- 响应参数说明;
 
| 参数名称 | 数据类型 | 说明 | 
|---|---|---|
| error_code | Int | 返回响应码 0: 成功 -1: 客户端错误 -2: 服务端错误  | 
| message | String | 返回响应信息 | 
| data | String | token,如果校验失败,返回空 | 
- 响应示例。
 
| 项目 | 详情 | 
|---|---|
| 报文格式 | JSON | 
| 报文内容 | { "data": "eyJhbGciOiJIUzUxMiIsImlhdCI6MTYy…", "error_code": 0, "message": { "zh": "获取token成功!", "en": "Get token successful!" } }  | 
2. 生成signature
需要登录上位机平台查看Access Key ID和Access Key Secret
- Python示例:
 
import hashlib
import hmac
import logging
# 配置日志记录器
LOGGER = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def generate_signature(sk: str, ak: str, timestamp: int, nonce: str) -> str:
    """
    生成数据的HMAC-SHA256签名
    Args:
        sk: 秘钥
        ak: 用户id
        timestamp: 时间戳(秒)
        nonce: UUID,长度不超过64
    Returns: 签名
    """
    try:
        if len(nonce) > 64:
            LOGGER.error('The length of nonce is too long: {}, limit is 64'.format(len(nonce)))
            return None
        message = '{}:{}:{}'.format(ak, timestamp, nonce)
        sk_bytes = sk.encode('utf-8')
        data_bytes = message.encode('utf-8')
        hmac_obj = hmac.new(sk_bytes, data_bytes, hashlib.sha256)
        signature = hmac_obj.hexdigest()
        return signature
    except Exception as e:
        LOGGER.exception('generate_signature')
        return None
# 示例使用
sk = 'Access Key Secret'
ak = 'Access Key ID'
timestamp = int(time.time())
nonce = 'random_string'
signature = generate_signature(sk, ak, timestamp, nonce)
print('Signature:', signature)
- JAVA示例:
 
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
public class SignatureGenerator {
    public static String hmacSha256Hex(String data, String key) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        mac.init(secretKey);
        byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
        // Java 17+ 使用 HexFormat
//        return HexFormat.of().formatHex(hash);
        // Java 8/11 可用如下方式替代
        return bytesToHex(hash);
    }
    // Java 8/11 兼容的 hex 转换方法
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
    public static void main(String[] args) throws Exception {
        String ak = "67c027b8c380620a55590196";
        String sk = "ae1ca515-fe0a-437b-84b6-2af5e1177627";
        long timestamp = System.currentTimeMillis() / 1000;
        // UUID不能超过64位
        String nonce = UUID.fastUUID().toString();
        String message = ak + ":" + timestamp + ":" + nonce;
        String signature = hmacSha256Hex(message, sk);
        System.out.println("timestamp: " + timestamp);
        System.out.println("nonce: " + nonce);
        System.out.println("Signature: " + signature);
    }
}
- JavaScript示例:
 
    <script src="https://cdn.bootcss.com/crypto-js/3.1.9-1/crypto-js.js"></script>
    <script>
        var ak = 'ak';
        var sk = 'sk';
		var timestamp = 1722995536;
		var nonce = 'nekjwdfka';
		var message =`${ak}:${timestamp}:${nonce}`;
        var hash = CryptoJS.HmacSHA256(message, sk);
        var signature = CryptoJS.enc.Hex.stringify(hash);
    </script>
3. 获取系统时间戳
- 接口功能描述:获取系统时间;
 - 接口路径:[GET]http://云服务IP:9191/ks/proxy/system/time;
 - 请求参数: 无;
 - 响应参数说明;
 
| 参数名称 | 数据类型 | 说明 | 
|---|---|---|
| error_code | Int | 返回响应码 0: 成功 -1: 客户端错误 -2: 服务端错误  | 
| message | String | 返回响应信息 | 
| data | Int | 1722995536,时间戳:秒数 | 
- 响应示例。
 
| 项目 | 详情 | 
|---|---|
| 报文格式 | JSON | 
| 报文内容 | { "data": 1725246379, "error_code": 0, "message": { "zh": "查询系统时间成功!", "en": "Query system time successful!" } }  | 
4. 更新token
- 接口功能描述:更新token(token过期时间为1小时);
 - 接口路径:[GET]http://云服务IP:9191/ks/proxy/user/token_by_token;
 - 请求参数:
 
| 参数名称 | 数据类型 | 是否必须 | 说明 | 
|---|---|---|---|
| Authorization | String | 是 | ‘Bearer ’+ token; token通过获取token接口获取 | 
- 响应参数说明;
 
| 参数名称 | 数据类型 | 说明 | 
|---|---|---|
| error_code | Int | 返回响应码 0: 成功 -1: 客户端错误 -2: 服务端错误  | 
| message | String | 返回响应信息 | 
| data | Object | 返回数据 | 
l 响应示例。
| 项目 | 详情 | 
|---|---|
| 报文格式 | JSON | 
| 报文内容 | { "data": "eyJhbGciOiJIUzUxMiIsImlhdCI6MTYy…", "error_code": 0, "message": { "zh": "获取token成功!", "en": "Get token successful!" } }  | 
5. Postman快速获取token
打开postman中的http://云服务IP:9191/ks/proxy/user/token 接口,在此接口的Scripts标签页的Pre-request,如下图位置添加代码即可快速获取token。可将此接口设置为前置接口。

var CryptoJS = require('crypto-js');
var ak = "67c028f1c38062137d1b88d1";  // 上位机后台查看
var sk = "19f07f37-5b13-4482-94fb-3f7ad0b5d547"; // 上位机后台查看
var timestamp = Math.floor(Date.now() / 1000);
var nonce = Math.random().toString(36).substring(2, 18); 
var message = `${ak}:${timestamp.toString()}:${nonce}`;
var hash = CryptoJS.HmacSHA256(message, sk);
var signature = CryptoJS.enc.Hex.stringify(hash);
console.log("ak:", ak);
console.log("timestamp:", timestamp);
console.log("nonce:", nonce);
console.log("signature:", signature);
// 清除旧的查询参数
pm.request.url.query.clear();
pm.request.url.addQueryParams([
    { key: 'ak', value: ak },
    { key: 'timestamp', value: timestamp.toString() },
    { key: 'nonce', value: nonce },
    { key: 'signature', value: signature }
]);
真诚点赞 诚不我欺
                
回复