PieBox
文档中心

HMAC-SHA256 签名认证

服务端集成的高安全性认证方式

适用于自研应用的服务端集成场景,安全性高于 API Key。日常使用 Claude Code 等工具只需 API Key,无需此方式。

认证流程与请求 Headers

认证流程:

  1. 获取 appIdappSecret(申请时选择「其他」场景)
  2. 构建签名字符串
  3. 使用 appSecret 对签名字符串进行 HMAC-SHA256 签名
  4. 将认证信息放入请求 Headers

请求 Headers:

Header说明
X-App-Id应用 ID
X-TimestampUnix 时间戳(秒),有效期 5 分钟
X-Nonce随机字符串,防止重放攻击,每次请求必须不同
AuthorizationHMAC-SHA256 {signature}

签名计算

签名字符串格式(各字段用换行符 \n 拼接):

{HTTP_METHOD}\n{PATH}\n{TIMESTAMP}\n{NONCE}\n{APP_ID}

字段说明:

字段说明示例
HTTP_METHOD请求方法(大写)POST
PATH请求路径(不含域名和查询参数)/chat/completions
TIMESTAMP当前 Unix 时间戳(秒)1706745600
NONCE32 位随机十六进制字符串a1b2c3d4e5f67890abcdef1234567890
APP_ID应用 IDapp_xxxxx

计算步骤:

  1. 按上述格式拼接签名字符串(使用真实的换行符 \n,不是字面的反斜杠 n)
  2. 使用 appSecret 作为密钥,对签名字符串进行 HMAC-SHA256 运算
  3. 将结果转为十六进制字符串(小写)

代码示例

Node.js

import { createHmac, randomBytes } from 'crypto'

const APP_ID = '<your-app-id>'
const APP_SECRET = '<your-app-secret>'
const BASE_URL = 'https://tokenhub.piegateway.me'

function computeSignature(
  method: string,
  path: string,
  timestamp: number,
  nonce: string,
  appId: string,
  appSecret: string
): string {
  const signatureString = `${method}\n${path}\n${timestamp}\n${nonce}\n${appId}`
  return createHmac('sha256', appSecret).update(signatureString).digest('hex')
}

function generateAuthHeaders(method: string, path: string) {
  const timestamp = Math.floor(Date.now() / 1000)
  const nonce = randomBytes(16).toString('hex')
  const signature = computeSignature(method, path, timestamp, nonce, APP_ID, APP_SECRET)

  return {
    'X-App-Id': APP_ID,
    'X-Timestamp': timestamp.toString(),
    'X-Nonce': nonce,
    Authorization: `HMAC-SHA256 ${signature}`,
    'Content-Type': 'application/json'
  }
}

// 使用示例
const path = '/chat/completions'
const headers = generateAuthHeaders('POST', path)

const response = await fetch(`${BASE_URL}${path}`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    model: 'claude-haiku-4-5',
    messages: [{ role: 'user', content: '你好' }],
    max_tokens: 100
  })
})

const result = await response.json()
console.log(result)

Bash

#!/bin/bash
APP_ID="<your-app-id>"
APP_SECRET="<your-app-secret>"
BASE_URL="https://tokenhub.piegateway.me"
METHOD="POST"
API_PATH="/chat/completions"
TIMESTAMP=$(date +%s)
NONCE=$(openssl rand -hex 16)

# 构建签名字符串
SIGNATURE_STRING=$(printf "%s\n%s\n%s\n%s\n%s" "$METHOD" "$API_PATH" "$TIMESTAMP" "$NONCE" "$APP_ID")

# 计算 HMAC-SHA256 签名(兼容 macOS 和 Linux)
SIGNATURE=$(echo -n "$SIGNATURE_STRING" | openssl dgst -sha256 -hmac "$APP_SECRET" | sed 's/^.*= //')

curl -X POST "{BASE_URL}{API_PATH}" \
  -H "X-App-Id: ${APP_ID}" \
  -H "X-Timestamp: ${TIMESTAMP}" \
  -H "X-Nonce: ${NONCE}" \
  -H "Authorization: HMAC-SHA256 ${SIGNATURE}" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-haiku-4-5",
    "messages": [{"role": "user", "content": "你好"}],
    "max_tokens": 100
  }'

WebSocket 认证

WebSocket 连接同样支持 HMAC-SHA256 签名认证:

方式一:Headers(推荐)

const ws = new WebSocket('wss://tokenhub.piegateway.me/ws/...', {
  headers: generateAuthHeaders('GET', '/ws/...')
})

方式二:Query 参数(浏览器环境)

const params = new URLSearchParams({
  'X-App-Id': APP_ID,
  'X-Timestamp': timestamp.toString(),
  'X-Nonce': nonce,
  Authorization: `HMAC-SHA256 ${signature}`
})
const ws = new WebSocket(`wss://tokenhub.piegateway.me/ws/...?${params}`)

安全约束与错误码

安全约束:

约束说明
时间戳有效期5 分钟(300 秒),超时请求将被拒绝
Nonce 防重放同一 nonce 最多使用 3 次,过期时间 300 秒
签名大小写签名结果为小写十六进制字符串

HMAC 认证错误码:

状态码错误类型说明
401missing_auth_headers缺少必要的认证头
401invalid_timestamp时间戳过期(超过 5 分钟)
401nonce_reusedNonce 重复使用(防重放)
401invalid_appappId 不存在
401invalid_signature签名验证失败(检查 appSecret 和签名字符串格式)
403app_disabled应用已被禁用