磐石CDN 开发文档PanshiCDN Docs

URL 鉴权对接URL Signing

开启 URL 鉴权后,只有带正确签名、且未过期的链接才能访问,其余请求返回 403,可防止资源被盗链和批量下载。签名由你的服务端用鉴权密钥生成,CDN 节点校验。支持 A / B / C / F 四种格式,与阿里云、腾讯云 CDN 及 GoEdge 的签名格式兼容,迁移过来无需改业务代码。With URL signing on, only links carrying a valid, unexpired signature are served; everything else gets 403. This stops hotlinking and bulk scraping. Your server generates the signature with the signing key, and CDN nodes verify it. Four formats are supported (A / B / C / F), compatible with Alibaba Cloud CDN, Tencent Cloud CDN and GoEdge, so you can migrate without changing your code.

概述Overview

类型Type链接格式URL format签名原文String signed
A/path?auth_key=ts-rand-uid-md5hashURI-ts-rand-uid-KEY
A (GoEdge)/path?auth_key=ts-rand-md5hashURI@ts@rand@KEY
B/YYYYMMDDHHMM/md5hash/pathKEY + YYYYMMDDHHMM + URI
C/md5hash/hexts/path 或or /path?KEY1=md5hash&KEY2=hextsKEY + URI + hexts
F/path?sign=md5hash&time=tsKEY + URI + ts

开启鉴权Turning it on

控制台 → 域名详情 →「访问控制」→「URL 鉴权」:选择类型,填写主密钥(6~128 位)和有效期(秒),保存后自动下发到全部节点。也可通过 API 修改域名配置的 adv.auth:

Console → domain details → "Access control" → "URL signing": choose a type, set the primary key (6–128 characters) and validity (seconds), then save. It is pushed to all nodes automatically. You can also set adv.auth in the domain config via the API:

"adv": {"auth": {
  "enabled": true,
  "type": "a",            // a / b / c / f
  "key": "YourPrimaryKey",
  "key2": "",             // backup key, optional
  "ttl": 1800,            // seconds
  "param": "auth_key",    // A: signature param; C: default KEY1; F: default sign
  "time_param": "",       // C: default KEY2; F: default time
  "time_format": "dec"    // F only: dec / hex
}}

通用约定Common rules

A 型(推荐)Type A (recommended)

http://cdn.example.com/video/1.mp4?auth_key={timestamp}-{rand}-{uid}-{md5hash}
md5hash = md5("/video/1.mp4-{timestamp}-{rand}-{uid}-{KEY}")

rand 为随机串(字母数字或下划线,建议 UUID 去掉横线),uid 一般填 0。签名参数名默认 auth_key,可在配置中修改。从 GoEdge 迁移来的三段格式 auth_key=ts-rand-md5(URI@ts@rand@KEY) 也能直接通过。

rand is a random string (letters, digits or underscore; a UUID without dashes works well). uid is usually 0. The parameter name defaults to auth_key and can be changed. The three-part GoEdge format auth_key=ts-rand-md5(URI@ts@rand@KEY) is also accepted.

import hashlib, time, uuid

def sign_a(url_path, key, uid="0"):
    ts, rand = int(time.time()), uuid.uuid4().hex
    h = hashlib.md5(f"{url_path}-{ts}-{rand}-{uid}-{key}".encode()).hexdigest()
    return f"{url_path}?auth_key={ts}-{rand}-{uid}-{h}"

print("https://cdn.example.com" + sign_a("/video/1.mp4", "YourPrimaryKey"))
<?php
function sign_a($path, $key, $uid = '0') {
    $ts = time(); $rand = bin2hex(random_bytes(16));
    $h = md5("$path-$ts-$rand-$uid-$key");
    return "$path?auth_key=$ts-$rand-$uid-$h";
}
echo 'https://cdn.example.com' . sign_a('/video/1.mp4', 'YourPrimaryKey');
func signA(path, key string) string {
	ts := time.Now().Unix()
	b := make([]byte, 16)
	rand.Read(b)
	r := hex.EncodeToString(b)
	sum := md5.Sum([]byte(fmt.Sprintf("%s-%d-%s-0-%s", path, ts, r, key)))
	return fmt.Sprintf("%s?auth_key=%d-%s-0-%x", path, ts, r, sum)
}
const crypto = require('crypto');
function signA(path, key, uid = '0') {
  const ts = Math.floor(Date.now() / 1000), rand = crypto.randomBytes(16).toString('hex');
  const h = crypto.createHash('md5').update(`${path}-${ts}-${rand}-${uid}-${key}`).digest('hex');
  return `${path}?auth_key=${ts}-${rand}-${uid}-${h}`;
}
static String signA(String path, String key) throws Exception {
    long ts = System.currentTimeMillis() / 1000;
    String rand = java.util.UUID.randomUUID().toString().replace("-", "");
    String raw = path + "-" + ts + "-" + rand + "-0-" + key;
    byte[] d = java.security.MessageDigest.getInstance("MD5").digest(raw.getBytes("UTF-8"));
    StringBuilder h = new StringBuilder();
    for (byte b : d) h.append(String.format("%02x", b));
    return path + "?auth_key=" + ts + "-" + rand + "-0-" + h;
}

链接原本带有查询参数时,把 auth_key 追加在后面即可,例如 /a.jpg?w=200&auth_key=...;签名原文仍只用路径 /a.jpg。

If the URL already has query parameters, just append auth_key, e.g. /a.jpg?w=200&auth_key=.... The signed string still uses only the path /a.jpg.

B 型Type B

http://cdn.example.com/{YYYYMMDDHHMM}/{md5hash}/video/1.mp4
md5hash = md5(KEY + "{YYYYMMDDHHMM}" + "/video/1.mp4")

时间为北京时间(UTC+8),精确到分钟,例如 202611281530。

The time is Beijing time (UTC+8) to the minute, e.g. 202611281530.

import hashlib, datetime

def sign_b(path, key):
    t = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=8))).strftime("%Y%m%d%H%M")
    h = hashlib.md5(f"{key}{t}{path}".encode()).hexdigest()
    return f"/{t}/{h}{path}"
<?php
function sign_b($path, $key) {
    $t = (new DateTime('now', new DateTimeZone('Asia/Shanghai')))->format('YmdHi');
    return "/$t/" . md5($key . $t . $path) . $path;
}

C 型Type C

# 路径形式# path form
http://cdn.example.com/{md5hash}/{hexts}/video/1.mp4
# 参数形式# query form
http://cdn.example.com/video/1.mp4?KEY1={md5hash}&KEY2={hexts}
md5hash = md5(KEY + "/video/1.mp4" + hexts)

hexts 为 Unix 时间戳的十六进制(小写),例如 1764316800 → 69295680。参数名可在配置中修改(默认 KEY1 / KEY2)。

hexts is the Unix timestamp in lowercase hex, e.g. 1764316800 → 69295680. Parameter names are configurable (default KEY1 / KEY2).

import hashlib, time

def sign_c(path, key):
    hx = format(int(time.time()), "x")
    h = hashlib.md5(f"{key}{path}{hx}".encode()).hexdigest()
    return f"/{h}/{hx}{path}"          # or f"{path}?KEY1={h}&KEY2={hx}"
<?php
function sign_c($path, $key) {
    $hx = dechex(time());
    return '/' . md5($key . $path . $hx) . "/$hx$path";
}

F 型Type F

http://cdn.example.com/video/1.mp4?sign={md5hash}&time={ts}
md5hash = md5(KEY + "/video/1.mp4" + ts)

ts 默认是十进制 Unix 时间戳;配置 time_format: "hex" 时为十六进制。参数名可改(默认 sign / time)。签名原文中的 ts 与链接里的写法保持一致。

ts is a decimal Unix timestamp by default, or hex with time_format: "hex". Parameter names are configurable (default sign / time). Use ts in the signed string exactly as it appears in the URL.

import hashlib, time
def sign_f(path, key):
    ts = str(int(time.time()))
    return f"{path}?sign={hashlib.md5((key + path + ts).encode()).hexdigest()}&time={ts}"

密钥轮换Key rotation

需要更换密钥时:先把新密钥填到「备用密钥」并保存 → 业务改用新密钥签名 → 等旧链接全部过期后,把新密钥移到主密钥、清空备用密钥。期间两个密钥签出的链接都能访问。

To change keys: put the new key in "Backup key" and save → switch your app to sign with the new key → once old links have expired, move the new key to the primary slot and clear the backup. Links signed with either key work during the switch.

排查Troubleshooting

现象Symptom检查Check
刚生成的链接就 403Fresh link returns 403密钥是否一致;签名原文的 URI 是否和实际访问路径完全一致(大小写、开头的 /、是否多了域名);md5 是否小写Same key? Does the URI in the signed string match the requested path exactly (case, leading /, no host)? Is the md5 lowercase?
过一会儿才 403403 after a while有效期是否太短;生成签名的服务器时间是否偏慢;B 型是否用了北京时间TTL too short? Is the signing server's clock behind? For type B, did you use Beijing time?
中文文件名 403403 on non-ASCII filenames签名原文用编码前或编码后的路径都可以,但链接中必须是合法的 URL 编码Sign either the encoded or decoded path, but the URL itself must be properly percent-encoded

访问日志中鉴权失败的请求状态码为 403,可在域名详情「日志」中按状态码筛选查看。

Failed requests are logged with status 403; filter by status in the domain's "Logs" tab.