AccessKey 请求签名
本页内容
使用 SDK 时,由 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 时自动生成。 |
X-Api-Date |
是 | UTC 时间,格式 YYYY-MM-DDTHH:mm:ssZ。与服务器的时间偏差最多 300 秒。 查看取值约束
|
X-Api-Nonce |
是 | 每次请求生成 16 个随机字节,转为 32 位小写十六进制。重试时重新生成。 查看取值约束
|
X-Api-Content-Sha256 |
是 | 实际发送的正文原始字节的 SHA-256 小写十六进制。GET 计算空字节串。 查看取值约束
|
X-Api-Environment |
是 | 生产环境传 production。 查看取值约束
|
X-Api-Security-Token |
否 | 仅使用 AKT 时必传。令牌放入此头,令牌摘要追加到签名串。 查看取值约束
|
POST 另传 Content-Type: application/json 与本次已保存的 X-Api-Idempotency-Key。使用临时 AccessKey 时,还需 X-Api-Security-Token;长期 AccessKey 不传该头。
计算规范请求与签名
- HTTP 方法转为大写,主机名使用小写。使用实际 API 路径,不含查询串;默认 HTTPS 端口不写入主机名。
- 查询参数按名称升序排列,键和值分别按 RFC 3986 编码。空格写成
%20,同名参数只允许出现一次;没有查询参数时该行留空。 - 先确定要发送的正文原始字节,再计算 SHA-256 小写十六进制。GET 对空字节串计算摘要。发送时不能再次序列化成另一份正文。
- 按下方顺序用单个换行符 LF 连接各行。GET 的幂等键为空,因此长期 AccessKey 的 GET 规范串以 LF 结尾。
- 临时 AccessKey 在最后再追加 LF 和安全令牌的 SHA-256 十六进制摘要。使用完整 Secret 的 UTF-8 字节计算 HMAC-SHA256,结果转为小写十六进制。
CS1-HMAC-SHA256
HTTP 方法
主机名
路径
规范查询串
X-Api-Date
X-Api-Nonce
正文 SHA-256
production
幂等键Authorization: CS1-HMAC-SHA256 Credential=<AccessKey ID>,Signature=<64 位小写十六进制签名>Secret 只用于本地计算,不发送给 API。请求时间使用 UTC;每次尝试重新生成时间、nonce 和认证签名,同一次业务重试仍保留原幂等键。
运行参考实现
先按快速入门完成一次只读调用,再将下方实现作为比对依据。它包含签名、HTTPS 请求和错误处理。
下载 Python 标准库实现查看完整实现
"""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
排查签名不一致
逐项比对主机名、路径、查询编码、正文原始字节和换行位置。GET 的空正文 SHA-256 是 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855。不要使用分发短链或存储域名调用业务 API,也不要把临时令牌遗漏在规范串之外。