Infilake OpenAPI Auth SDK 使用说明

本文档介绍如何安装和使用 Infilake OpenAPI 认证 SDK,用于生成 HMAC-SHA256 签名的请求头。


目录


Python SDK

Python 安装

方式一:pip 安装

pip install infilake-openapi-auth

方式二:从源码安装

# 下载 SDK 源码后
cd sdk/python
pip install .

方式三:使用 uv 安装(推荐)

# 安装 uv
# Windows:
powershell -c "irm https://astral.sh/uv/install.ps1 | iex"
# macOS/Linux:
curl -LsSf https://astral.sh/uv/install.sh | sh

# 创建虚拟环境并安装
cd sdk/python
uv venv
uv pip install .

Python 使用示例

基础用法

from infilake_openapi_auth import AuthSDK

# 初始化 SDK(使用您的密钥)
sdk = AuthSDK("your-hmac-secret-key")

# 生成请求头
headers = sdk.get_headers("/api/v1/users", "GET")
print(headers)
# 输出: {'X-Timestamp': '20260116T120000Z', 'X-Authorization': 'xxxxxxxx'}

结合 requests 库发送请求

import requests
from infilake_openapi_auth import AuthSDK

# 初始化
sdk = AuthSDK("your-hmac-secret-key")

# API 配置
base_url = "https://api.example.com"
endpoint = "/api/v1/users"

# 生成认证头
auth_headers = sdk.get_headers(endpoint, "GET")

# 发送请求
response = requests.get(
    f"{base_url}{endpoint}",
    headers=auth_headers
)
print(response.json())

POST 请求示例

import requests
from infilake_openapi_auth import AuthSDK

sdk = AuthSDK("your-hmac-secret-key")

endpoint = "/api/v1/users"
auth_headers = sdk.get_headers(endpoint, "POST")

# 添加其他请求头
auth_headers["Content-Type"] = "application/json"

response = requests.post(
    "https://api.example.com" + endpoint,
    headers=auth_headers,
    json={"name": "张三", "email": "zhangsan@example.com"}
)
print(response.json())

使用 sign 方法获取详细结果

from infilake_openapi_auth import AuthSDK

sdk = AuthSDK("your-hmac-secret-key")

# sign 方法返回 AuthResult 对象
result = sdk.sign("/api/v1/data", "PUT")

print(f"时间戳: {result.x_timestamp}")
print(f"签名: {result.x_authorization}")

Java SDK

Java 安装

方式一:直接引用 JAR 包

  1. 下载 auth-sdk-1.0.0.jar 文件
  2. 将 JAR 包添加到项目的 libs 目录
  3. 在项目中引用该 JAR 包

IDE 配置:

命令行编译运行:

# 编译
javac -cp libs/auth-sdk-1.0.0.jar YourApp.java

# 运行 (Windows)
java -cp "libs/auth-sdk-1.0.0.jar;." YourApp

# 运行 (macOS/Linux)
java -cp "libs/auth-sdk-1.0.0.jar:." YourApp

方式二:Maven 本地仓库安装

# 安装到本地 Maven 仓库
mvn install:install-file \
  -Dfile=auth-sdk-1.0.0.jar \
  -DgroupId=com.infilake.openapi \
  -DartifactId=auth-sdk \
  -Dversion=1.0.0 \
  -Dpackaging=jar

然后在 pom.xml 中添加依赖:

<dependency>
    <groupId>com.infilake.openapi</groupId>
    <artifactId>auth-sdk</artifactId>
    <version>1.0.0</version>
</dependency>

方式三:Gradle 配置

// build.gradle
dependencies {
    implementation files('libs/auth-sdk-1.0.0.jar')
}

Java 使用示例

基础用法

import com.infilake.openapi.auth.AuthSDK;
import java.util.Map;

public class Example {
    public static void main(String[] args) {
        // 初始化 SDK(使用您的密钥)
        AuthSDK sdk = new AuthSDK("your-hmac-secret-key");

        // 生成请求头
        Map<String, String> headers = sdk.getHeaders("/api/v1/users", "GET");

        System.out.println("X-Timestamp: " + headers.get("X-Timestamp"));
        System.out.println("X-Authorization: " + headers.get("X-Authorization"));
    }
}

结合 HttpURLConnection 发送请求

import com.infilake.openapi.auth.AuthSDK;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class HttpExample {
    public static void main(String[] args) throws Exception {
        AuthSDK sdk = new AuthSDK("your-hmac-secret-key");

        String baseUrl = "https://api.example.com";
        String endpoint = "/api/v1/users";

        // 生成认证头
        Map<String, String> authHeaders = sdk.getHeaders(endpoint, "GET");

        // 创建连接
        URL url = new URL(baseUrl + endpoint);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");

        // 设置认证头
        for (Map.Entry<String, String> entry : authHeaders.entrySet()) {
            conn.setRequestProperty(entry.getKey(), entry.getValue());
        }

        // 读取响应
        BufferedReader reader = new BufferedReader(
            new InputStreamReader(conn.getInputStream()));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        System.out.println(response.toString());
    }
}

结合 OkHttp 发送请求

import com.infilake.openapi.auth.AuthSDK;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.util.Map;

public class OkHttpExample {
    public static void main(String[] args) throws Exception {
        AuthSDK sdk = new AuthSDK("your-hmac-secret-key");
        OkHttpClient client = new OkHttpClient();

        String endpoint = "/api/v1/users";
        Map<String, String> authHeaders = sdk.getHeaders(endpoint, "GET");

        Request request = new Request.Builder()
            .url("https://api.example.com" + endpoint)
            .header("X-Timestamp", authHeaders.get("X-Timestamp"))
            .header("X-Authorization", authHeaders.get("X-Authorization"))
            .build();

        try (Response response = client.newCall(request).execute()) {
            System.out.println(response.body().string());
        }
    }
}

POST 请求示例

import com.infilake.openapi.auth.AuthSDK;
import okhttp3.*;
import java.util.Map;

public class PostExample {
    public static void main(String[] args) throws Exception {
        AuthSDK sdk = new AuthSDK("your-hmac-secret-key");
        OkHttpClient client = new OkHttpClient();

        String endpoint = "/api/v1/users";
        Map<String, String> authHeaders = sdk.getHeaders(endpoint, "POST");

        // 构建 JSON 请求体
        MediaType JSON = MediaType.get("application/json; charset=utf-8");
        String jsonBody = "{\"name\": \"张三\", \"email\": \"zhangsan@example.com\"}";
        RequestBody body = RequestBody.create(jsonBody, JSON);

        Request request = new Request.Builder()
            .url("https://api.example.com" + endpoint)
            .header("X-Timestamp", authHeaders.get("X-Timestamp"))
            .header("X-Authorization", authHeaders.get("X-Authorization"))
            .post(body)
            .build();

        try (Response response = client.newCall(request).execute()) {
            System.out.println(response.body().string());
        }
    }
}

使用 sign 方法获取详细结果

import com.infilake.openapi.auth.AuthSDK;
import com.infilake.openapi.auth.AuthSDK.AuthResult;

public class SignExample {
    public static void main(String[] args) {
        AuthSDK sdk = new AuthSDK("your-hmac-secret-key");

        // sign 方法返回 AuthResult 对象
        AuthResult result = sdk.sign("/api/v1/data", "PUT");

        System.out.println("时间戳: " + result.getXTimestamp());
        System.out.println("签名: " + result.getXAuthorization());
    }
}

签名说明

签名算法

SDK 使用 HMAC-SHA256 算法生成请求签名,流程如下:

  1. 生成时间戳:格式为 YYYYMMDDTHHMMSSZ(UTC 时间)
  2. 构建待签名字符串
    {HTTP方法}\n{请求路径}\n{时间戳}\n
    
  3. 计算签名:使用 HMAC-SHA256 算法和密钥对字符串签名
  4. Base64 编码:将签名结果进行 Base64 编码

请求头说明

Header 说明
X-Timestamp 请求时间戳,格式:YYYYMMDDTHHMMSSZ
X-Access-Key 访问密钥标识(由服务方提供)
X-Authorization Base64 编码的 HMAC-SHA256 签名

示例

假设:

待签名字符串:

GET
/api/v1/users
20260116T120000Z

生成的请求头:

X-Timestamp: 20260116T120000Z
X-Authorization: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=

常见问题

Q: 签名验证失败怎么办?

  1. 确认密钥正确无误
  2. 确认请求路径与签名时使用的路径一致
  3. 确认 HTTP 方法大小写正确(如 GETPOST
  4. 检查服务器时间与客户端时间是否同步

Q: 时间戳有效期是多久?

请咨询 API 服务提供方,通常有效期为 5-15 分钟。

Q: 支持哪些 Java 版本?

Java 8 及以上版本。

Q: 支持哪些 Python 版本?

Python 3.8 及以上版本。

Q: 请求头的顺序有要求吗?

没有顺序要求,请求头须包含:

  1. X-Timestamp
  2. X-Access-Key
  3. X-Authorization

Python 示例:

import requests
from infilake_openapi_auth import AuthSDK
from collections import OrderedDict

sdk = AuthSDK("your-hmac-secret-key")
result = sdk.sign("/api/v1/users", "GET")

# 按顺序构建请求头
headers = OrderedDict([
    ("X-Timestamp", result.x_timestamp),
    ("X-Access-Key", "your-access-key"),
    ("X-Authorization", result.x_authorization),
])

response = requests.get("https://api.example.com/api/v1/users", headers=headers)

Java 示例:

import com.infilake.openapi.auth.AuthSDK;
import com.infilake.openapi.auth.AuthSDK.AuthResult;
import java.util.LinkedHashMap;
import java.util.Map;

AuthSDK sdk = new AuthSDK("your-hmac-secret-key");
AuthResult result = sdk.sign("/api/v1/users", "GET");

// 使用 LinkedHashMap 
Map<String, String> headers = new LinkedHashMap<>();
headers.put("X-Timestamp", result.getXTimestamp());
headers.put("X-Access-Key", "your-access-key");
headers.put("X-Authorization", result.getXAuthorization());