跳转到主要内容
1签 (OneSign)

AccessKey 请求签名

本页内容

SDK 会计算签名。自行实现 HTTP 客户端时,先按规则构造 CS1-HMAC-SHA256 规范串,再用固定示例核对本地输出。

何时需要自行签名

现有 SDK 已实现 CS1 签名,正常使用 SDK 不必重复计算。本页适用于自行实现 HTTP 客户端,或排查两个实现生成的签名为何不一致。OAuth Bearer 使用另一种认证方式,不与 AccessKey 请求头混用。

准备公共请求头

调用地址使用网站主域名 https://www.onesignios.com。GET 不发送正文,POST 使用 UTF-8 JSON 对象。公共请求头如下,类型和精确格式可展开查看。

字段必填说明
Authorization 是

AccessKey 调用的认证签名,格式为 CS1-HMAC-SHA256 Credential=密钥ID,Signature=签名。使用 SDK 时自动生成。

类型:string · 位置:Header

X-Api-Date 是

UTC 时间,格式 YYYY-MM-DDTHH:mm:ssZ。与服务器的时间偏差最多 300 秒。

类型:string · 位置:Header

查看取值约束
  • 数据格式 date-time
X-Api-Nonce 是

每次请求生成 16 个随机字节,转为 32 位小写十六进制。重试时重新生成。

类型:string · 位置:Header

查看取值约束
  • 格式 ^[a-f0-9]{32}$
X-Api-Content-Sha256 是

实际发送的正文原始字节的 SHA-256 小写十六进制。GET 计算空字节串。

类型:string · 位置:Header

查看取值约束
  • 格式 ^[a-f0-9]{64}$
X-Api-Environment 是

生产环境传 production。

类型:string · 位置:Header

查看取值约束
  • 固定值 production
X-Api-Security-Token 否

仅使用 AKT 时必传。令牌放入此头,令牌摘要追加到签名串。

类型:string · 位置:Header

查看取值约束
  • 格式 ^CST_[A-Za-z0-9_-]{43}$

POST 另传 Content-Type: application/json 与本次已保存的 X-Api-Idempotency-Key。使用临时 AccessKey 时,还需 X-Api-Security-Token;长期 AccessKey 不传该头。

计算规范请求与签名

  1. HTTP 方法转为大写,主机名使用小写。使用实际 API 路径,不含查询串;默认 HTTPS 端口不写入主机名。
  2. 查询参数按名称升序排列,键和值分别按 RFC 3986 编码。空格写成 %20,同名参数只允许出现一次;没有查询参数时该行留空。
  3. 先确定要发送的正文原始字节,再计算 SHA-256 小写十六进制。GET 对空字节串计算摘要。发送时不能再次序列化成另一份正文。
  4. 按下方顺序用单个换行符 LF 连接各行。GET 的幂等键为空,因此长期 AccessKey 的 GET 规范串以 LF 结尾。
  5. 临时 AccessKey 在最后再追加 LF 和安全令牌的 SHA-256 十六进制摘要。使用完整 Secret 的 UTF-8 字节计算 HMAC-SHA256,结果转为小写十六进制。
规范串顺序
CS1-HMAC-SHA256
HTTP 方法
主机名
路径
规范查询串
X-Api-Date
X-Api-Nonce
正文 SHA-256
production
幂等键
Authorization 格式
Authorization: CS1-HMAC-SHA256 Credential=<AccessKey ID>,Signature=<64 位小写十六进制签名>

Secret 只用于本地计算,不发送给 API。请求时间使用 UTC;每次尝试重新生成时间、nonce 和认证签名,同一次业务重试仍保留原幂等键。

准备参考实现

将Python 标准库实现保存为 cloudsign_request.py。它提供 signed_headers() 来计算签名,以及 request() 来发送请求。希望先验证本地实现时,继续运行下方离线示例。准备调用自己账号时,按快速入门配置真实凭据并发送一次只读查询。

查看完整实现
cloudsign_request.py
"""Save as cloudsign_request.py and run with Python 3. No third-party package required."""
from datetime import datetime, timezone
import hashlib
import hmac
import http.client
import json
import os
import re
import secrets
from urllib.parse import quote, urlencode


class ApiError(RuntimeError):
    """Safe diagnostic fields. Write requests may already have reached the platform."""
    def __init__(self, status, code, request_id="", retry_after=0):
        self.status = status
        self.code = code
        self.request_id = request_id
        self.retry_after = retry_after
        super().__init__(f"HTTP {status} {code} request_id={request_id}")


def signed_headers(key_id, secret, host, method, path, params, body, date, nonce,
                   idempotency_key="", security_token=""):
    query = urlencode(sorted(params.items()), quote_via=quote, safe="-._~")
    digest = hashlib.sha256(body).hexdigest()
    lines = ["CS1-HMAC-SHA256", method, host, path, query, date, nonce, digest,
             "production", idempotency_key]
    headers = {"X-Api-Date": date, "X-Api-Nonce": nonce,
               "X-Api-Content-Sha256": digest, "X-Api-Environment": "production"}
    if security_token:
        lines.append(hashlib.sha256(security_token.encode()).hexdigest())
        headers["X-Api-Security-Token"] = security_token
    if method == "POST":
        headers.update({"Content-Type": "application/json",
                        "X-Api-Idempotency-Key": idempotency_key})
    signature = hmac.new(secret.encode(), "\n".join(lines).encode(), "sha256").hexdigest()
    headers["Authorization"] = f"CS1-HMAC-SHA256 Credential={key_id},Signature={signature}"
    return path + ("?" + query if query else ""), headers


def request(method, resource, params=None, payload=None, idempotency_key="", *, timeout=15):
    """Use the same payload and saved idempotency key for retries of one business action."""
    if method not in ("GET", "POST") or not re.fullmatch(r"/api/v1(?:/[A-Za-z0-9_-]+)+/?", resource):
        raise ValueError("Use a documented method and resource path")
    if method == "POST" and (not isinstance(payload, dict) or not re.fullmatch(r"[A-Za-z0-9_-]{16,64}", idempotency_key)):
        raise ValueError("POST requires a JSON object and a saved idempotency key")
    if method == "GET" and (payload is not None or idempotency_key):
        raise ValueError("GET has no request body or idempotency key")
    host = os.environ["CLOUDSIGN_HOST"].lower()  # 网站主域名,仅主机名
    if not re.fullmatch(r"[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?", host) or "." not in host:
        raise ValueError("CLOUDSIGN_HOST must be a hostname without https://, port or path")
    if isinstance(timeout, bool) or not 0 < timeout <= 60:
        raise ValueError("timeout must be greater than 0 and at most 60 seconds")
    body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode() if payload is not None else b""
    if len(body) > 16384:
        raise ValueError("JSON control body exceeds 16 KiB")
    path, headers = signed_headers(
        os.environ["CLOUDSIGN_ACCESS_KEY_ID"], os.environ["CLOUDSIGN_ACCESS_KEY_SECRET"],
        host, method, resource, params or {}, body,
        datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), secrets.token_hex(16),
        idempotency_key, os.environ.get("CLOUDSIGN_SECURITY_TOKEN", ""),
    )
    conn = http.client.HTTPSConnection(host, timeout=timeout)
    try:
        conn.request(method, path, body=body if method == "POST" else None, headers=headers)
        response = conn.getresponse()
        raw = response.read(2 * 1024 * 1024 + 1)
        if len(raw) > 2 * 1024 * 1024:
            raise ApiError(response.status, "InvalidResponse")
        try:
            envelope = json.loads(raw)
        except (ValueError, UnicodeDecodeError):
            raise ApiError(response.status, "InvalidResponse") from None
        if not isinstance(envelope, dict):
            raise ApiError(response.status, "InvalidResponse")
        request_id = envelope.get("request_id", "")
        if not isinstance(request_id, str) or not re.fullmatch(r"[a-f0-9]{32}", request_id):
            raise ApiError(response.status, "InvalidResponse")
        if response.status != 200:
            error = envelope.get("error")
            code = error.get("code") if isinstance(error, dict) else None
            if not isinstance(code, str) or not re.fullmatch(r"[A-Za-z][A-Za-z0-9_]{0,63}", code):
                raise ApiError(response.status, "InvalidResponse", request_id)
            retry = response.getheader("Retry-After") or ""
            seconds = min(86400, int(retry)) if re.fullmatch(r"[0-9]{1,6}", retry) else 0
            raise ApiError(response.status, code, request_id, seconds)
        if not isinstance(envelope.get("data"), dict):
            raise ApiError(response.status, "InvalidResponse", request_id)
        return envelope
    except (OSError, http.client.HTTPException):
        raise ApiError(0, "TransportError") from None
    finally:
        conn.close()


if __name__ == "__main__":
    try:
        answer = request("GET", "/api/v1/whoami")
        print(json.dumps(answer, ensure_ascii=False, indent=2))
    except ApiError as error:
        raise SystemExit(str(error)) from None

用固定示例离线核对签名

下面使用固定的演示数据,覆盖查询参数排序、中文与空格编码、空正文和行末换行。示例只调用签名函数,全程在本地运行。保存为 verify_signature.py,放在 cloudsign_request.py 同目录,再运行 python verify_signature.py。

verify_signature.py
from cloudsign_request import signed_headers

target, headers = signed_headers(
    key_id="AKP" + "a" * 40,
    secret="offline-doc-example",
    host="api.example.test",
    method="GET",
    path="/api/v1/apps",
    params={"search": "星河 阅读", "module": "distribution", "limit": "10"},
    body=b"",
    date="2026-01-01T00:00:00Z",
    nonce="0123456789abcdef" * 2,
)

print(target)
print(headers["Authorization"].split("Signature=", 1)[1])

比较两行输出。第一行是实际请求目标,第二行是 Authorization 头里的签名值。

预期输出
/api/v1/apps?limit=10&module=distribution&search=%E6%98%9F%E6%B2%B3%20%E9%98%85%E8%AF%BB
04f040e92e9bc7f6ca81223ce3f7ea1b2d4240c0685a5a54092949ae7654e400

如果在实现自己的客户端,将相同演示输入生成的请求目标和签名也与这两行比较。实际请求使用已授权的凭据、新生成的日期和 nonce,并对最终发送的字节签名。

需要验证 POST 或临时 AccessKey 时,把对应脚本保存为标题中的文件名,放在 cloudsign_request.py 同一目录运行。示例计算本地签名,并输出供比较的摘要。

核对含中文 JSON 正文的 POST 签名

以下示例使用已确定的 UTF-8 字节计算摘要。三行输出依次为请求目标、正文 SHA-256 和签名。接入实际请求时,将参与签名的同一份字节发送到平台。

verify_post_signature.py
from cloudsign_request import signed_headers

app_id = "A" + "1" * 32
body = '{"file_name":"星河阅读.ipa","size_bytes":65536,"transfer_mode":"multipart"}'.encode("utf-8")
target, headers = signed_headers(
    key_id="AKP" + "a" * 40,
    secret="offline-doc-example",
    host="api.example.test",
    method="POST",
    path=f"/api/v1/apps/{app_id}/uploads",
    params={},
    body=body,
    date="2026-01-01T00:00:00Z",
    nonce="fedcba9876543210" * 2,
    idempotency_key="sample-upload-00001",
)

print(target)
print(headers["X-Api-Content-Sha256"])
print(headers["Authorization"].split("Signature=", 1)[1])
预期输出
/api/v1/apps/A11111111111111111111111111111111/uploads
4f728c8c0fff62435b8dfaafe4a72c6d7706cdbbf5921e1938d3c157bc7e4458
a738a8581161a17841a3a035d5f17c69c07e51c9f01a1a30aff9fa6fd622f4a7
核对临时 AccessKey 的签名

三行输出依次为请求目标、安全令牌 SHA-256 和签名。临时凭据使用同一组 ID、Secret 和安全令牌。令牌原值放在 X-Api-Security-Token,它的摘要作为规范串最后一行。

verify_temporary_signature.py
import hashlib
from cloudsign_request import signed_headers

token = "CST_" + "A" * 43
target, headers = signed_headers(
    key_id="AKT" + "b" * 40,
    secret="offline-doc-example",
    host="api.example.test",
    method="GET",
    path="/api/v1/whoami",
    params={},
    body=b"",
    date="2026-01-01T00:00:00Z",
    nonce="0011223344556677" * 2,
    security_token=token,
)

print(target)
print(hashlib.sha256(token.encode("utf-8")).hexdigest())
print(headers["Authorization"].split("Signature=", 1)[1])
预期输出
/api/v1/whoami
54a9dbcfaed071315f2e8d2f973ca39f2a209c35f595a673e8ab8ddd2c46b157
75e91bc28e5121b7c4f760e92b62d53012a21f5229bbf4a34441b38382d4e89b

排查签名不一致

先用离线示例比对请求目标、摘要和签名。接着检查实际发送的域名、路径、查询串与正文字节,逐行核对规范串使用 LF。GET 空正文的 SHA-256 为 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855。

返回的错误码先核对什么
InvalidHost核对 SDK 配置的 HTTPS 来源、实际请求的 Host 和规范串中的主机名。三者应指向同一网站主域名。文件传输使用短期凭证返回的独立地址。
InvalidQuery按原始字段构造查询串,检查重复参数名、字面加号和百分号编码。可用特殊字符请求示例核对实际发送的字节。
InvalidCredentials检查实际服务进程加载的凭据和网站 HTTPS 主域名。POST 核对正文序列化结果。临时 AccessKey 同时核对安全令牌及规范串最后一行的摘要。
RequestExpired校准运行环境的 UTC 时钟,再使用当前日期和新 nonce 生成签名。
ReplayDetected重新生成日期、nonce 和签名。同一笔要恢复的写入继续使用原正文及幂等键。

需要排查线上问题时记录实际请求的错误码和 request_id。日志保留可核对的字段,隐藏 Secret、令牌与完整认证头。

更多连接与授权问题见认证和应用授权排查。