鉴权配置

更新时间:2025-01-14 15:07:34

鉴权令牌生成

在控制台新建API后,在“基础信息-鉴权配置”中可以找到该API鉴权所需使用的密钥。复制此密钥,它将在鉴权算法中作为加密密钥使用。根据提供的示例代码进行开发,完成开发后用户每次接口调用都需携带动态鉴权令牌。

开启密钥对鉴权后,系统将校验每个请求中的鉴权令牌,只有在有效期内且正确的令牌才会通过鉴权认证。

注意: 如果鉴权未通过,接口请求将被拒绝。

代码示例

配置

  1. 待鉴权API: http://your.domain/api
  2. 签名算法:HmacSHA256
  3. 密钥key:secret_key_str
  4. 鉴权位置:HEADER 对应鉴权头部key:X_Sam_Auth

示例代码

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()
# 加密后的byte数组转换为16进制字符串
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)

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);
    // 加密后的byte数组转换为16进制字符串
    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();
}

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"

请根据需要选择合适的语言进行集成,并确保请求头部信息准确无误。