生成令牌

本指南介绍了如何生成令牌,以及令牌的必填字段和选填字段。

如需创建令牌,您需要编写一个要签名的字符串,我们在本指南中将其称为有符号值。带符号的值包括描述您要保护的内容、带符号值的过期时间等参数。

您在创建令牌字符串时将使用带符号的值。您可以通过组合令牌的参数(例如签名值的对称密钥哈希消息身份验证代码 (HMAC))来创建令牌字符串。

媒体 CDN 使用最终组合的令牌来帮助保护您的内容。

创建令牌

  1. 串联包含必需令牌字段和所需可选令牌字段的字符串,以创建有符号值。请使用波浪号 ~ 字符分隔每个字段和所有参数。

  2. 使用 Ed25519 签名或对称密钥 HMAC 对已签名的值进行签名。

  3. 串联包含必需令牌字段和可选令牌字段的字符串,以编写令牌。请使用波浪号 ~ 字符分隔每个字段和所有参数。

    编写令牌时,带符号值和令牌字符串之间每个参数的值都相同,但存在以下例外情况:

    • FullPath
    • Headers

以下代码示例展示了如何以编程方式创建令牌:

Python

如需向媒体 CDN 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import base64
import datetime
import hashlib
import hmac

import cryptography.hazmat.primitives.asymmetric.ed25519 as ed25519


def base64_encoder(value: bytes) -> str:
    """
    Returns a base64-encoded string compatible with Media CDN.

    Media CDN uses URL-safe base64 encoding and strips off the padding at the
    end.
    """
    encoded_bytes = base64.urlsafe_b64encode(value)
    encoded_str = encoded_bytes.decode("utf-8")
    return encoded_str.rstrip("=")


def sign_token(
    base64_key: bytes,
    signature_algorithm: str,
    start_time: datetime.datetime = None,
    expiration_time: datetime.datetime = None,
    url_prefix: str = None,
    full_path: str = None,
    path_globs: str = None,
    session_id: str = None,
    data: str = None,
    headers: str = None,
    ip_ranges: str = None,
) -> str:
    """Gets the Signed URL Suffix string for the Media CDN' Short token URL requests.
    One of (`url_prefix`, `full_path`, `path_globs`) must be included in each input.
    Args:
        base64_key: Secret key as a base64 encoded string.
        signature_algorithm: Algorithm can be either `SHA1` or `SHA256` or `Ed25519`.
        start_time: Start time as a UTC datetime object.
        expiration_time: Expiration time as a UTC datetime object. If None, an expiration time 1 hour from now will be used.
        url_prefix: the URL prefix to sign, including protocol.
                    For example: http://example.com/path/ for URLs under /path or http://example.com/path?param=1
        full_path:  A full path to sign, starting with the first '/'.
                    For example: /path/to/content.mp4
        path_globs: a set of ','- or '!'-delimited path glob strings.
                    For example: /tv/*!/film/* to sign paths starting with /tv/ or /film/ in any URL.
        session_id: a unique identifier for the session
        data: data payload to include in the token
        headers: header name and value to include in the signed token in name=value format.  May be specified more than once.
                    For example: [{'name': 'foo', 'value': 'bar'}, {'name': 'baz', 'value': 'qux'}]
        ip_ranges: A list of comma separated ip ranges. Both IPv4 and IPv6 ranges are acceptable.
                    For example: "203.0.113.0/24,2001:db8:4a7f:a732/64"

    Returns:
        The Signed URL appended with the query parameters based on the
        specified URL prefix and configuration.
    """

    decoded_key = base64.urlsafe_b64decode(base64_key)
    algo = signature_algorithm.lower()

    # For most fields, the value we put in the token and the value we must sign
    # are the same.  The FullPath and Headers use a different string for the
    # value to be signed compared to the token.  To illustrate this difference,
    # we'll keep the token and the value to be signed separate.
    tokens = []
    to_sign = []

    # check for `full_path` or `path_globs` or `url_prefix`
    if full_path:
        tokens.append("FullPath")
        to_sign.append(f"FullPath={full_path}")
    elif path_globs:
        path_globs = path_globs.strip()
        field = f"PathGlobs={path_globs}"
        tokens.append(field)
        to_sign.append(field)
    elif url_prefix:
        field = "URLPrefix=" + base64_encoder(url_prefix.encode("utf-8"))
        tokens.append(field)
        to_sign.append(field)
    else:
        raise ValueError(
            "User Input Missing: One of `url_prefix`, `full_path` or `path_globs` must be specified"
        )

    # check & parse optional params
    if start_time:
        epoch_duration = start_time.astimezone(
            tz=datetime.timezone.utc
        ) - datetime.datetime.fromtimestamp(0, tz=datetime.timezone.utc)
        field = f"Starts={int(epoch_duration.total_seconds())}"
        tokens.append(field)
        to_sign.append(field)

    if not expiration_time:
        expiration_time = datetime.datetime.now() + datetime.timedelta(hours=1)
        epoch_duration = expiration_time.astimezone(
            tz=datetime.timezone.utc
        ) - datetime.datetime.fromtimestamp(0, tz=datetime.timezone.utc)
    else:
        epoch_duration = expiration_time.astimezone(
            tz=datetime.timezone.utc
        ) - datetime.datetime.fromtimestamp(0, tz=datetime.timezone.utc)
    field = f"Expires={int(epoch_duration.total_seconds())}"
    tokens.append(field)
    to_sign.append(field)

    if session_id:
        field = f"SessionID={session_id}"
        tokens.append(field)
        to_sign.append(field)

    if data:
        field = f"Data={data}"
        tokens.append(field)
        to_sign.append(field)

    if headers:
        header_names = []
        header_pairs = []
        for each in headers:
            header_names.append(each["name"])
            header_pairs.append("%s=%s" % (each["name"], each["value"]))
        tokens.append(f"Headers={','.join(header_names)}")
        to_sign.append(f"Headers={','.join(header_pairs)}")

    if ip_ranges:
        field = f"IPRanges={base64_encoder(ip_ranges.encode('ascii'))}"
        tokens.append(field)
        to_sign.append(field)

    # generating token
    to_sign = "~".join(to_sign)
    to_sign_bytes = to_sign.encode("utf-8")
    if algo == "ed25519":
        digest = ed25519.Ed25519PrivateKey.from_private_bytes(decoded_key).sign(
            to_sign_bytes
        )
        tokens.append("Signature=" + base64_encoder(digest))
    elif algo == "sha256":
        signature = hmac.new(
            decoded_key, to_sign_bytes, digestmod=hashlib.sha256
        ).hexdigest()
        tokens.append("hmac=" + signature)
    elif algo == "sha1":
        signature = hmac.new(
            decoded_key, to_sign_bytes, digestmod=hashlib.sha1
        ).hexdigest()
        tokens.append("hmac=" + signature)
    else:
        raise ValueError(
            "Input Missing Error: `signature_algorithm` can only be one of `sha1`, `sha256` or `ed25519`"
        )
    return "~".join(tokens)

Java

如需向媒体 CDN 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Optional;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters;
import org.bouncycastle.crypto.signers.Ed25519Signer;
import org.bouncycastle.util.encoders.Hex;

public class DualToken {

  public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException {
    // TODO(developer): Replace these variables before running the sample.
    // Secret key as a base64 encoded string.
    byte[] base64Key = new byte[]{};
    // Algorithm can be one of these: SHA1, SHA256, or Ed25519.
    String signatureAlgorithm = "ed25519";
    // (Optional) Start time as a UTC datetime object.
    DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
    Optional<Instant> startTime = Optional.empty();
    // Expiration time as a UTC datetime object.
    // If None, an expiration time that's an hour after the current time is used.
    Instant expiresTime = Instant.from(formatter.parse("2022-09-13T12:00:00Z"));

    // ONE OF (`urlPrefix`, `fullPath`, `pathGlobs`) must be included in each input.
    // The URL prefix and protocol to sign.
    // For example: http://example.com/path/ for URLs under /path or http://example.com/path?param=1
    Optional<String> urlPrefix = Optional.empty();
    // A full path to sign, starting with the first '/'.
    // For example: /path/to/content.mp4
    Optional<String> fullPath = Optional.of("http://10.20.30.40/");
    // A set of path glob strings delimited by ',' or '!'.
    // For example: /tv/*!/film/* to sign paths starting with /tv/ or /film/ in any URL.
    Optional<String> pathGlobs = Optional.empty();

    // (Optional) A unique identifier for the session.
    Optional<String> sessionId = Optional.empty();
    // (Optional) Data payload to include in the token.
    Optional<String> data = Optional.empty();
    // (Optional) Header name and value to include in the signed token in name=value format.
    // May be specified more than once.
    // For example: [{'name': 'foo', 'value': 'bar'}, {'name': 'baz', 'value': 'qux'}]
    Optional<List<Header>> headers = Optional.empty();
    // (Optional) A list of comma-separated IP ranges. Both IPv4 and IPv6 ranges are acceptable.
    // For example: "203.0.113.0/24,2001:db8:4a7f:a732/64"
    Optional<String> ipRanges = Optional.empty();

    DualToken.signToken(
        base64Key,
        signatureAlgorithm,
        startTime,
        expiresTime,
        urlPrefix,
        fullPath,
        pathGlobs,
        sessionId,
        data,
        headers,
        ipRanges);
  }

  // Gets the signed URL suffix string for the Media CDN short token URL requests.
  // Result:
  //     The signed URL appended with the query parameters based on the
  // specified URL prefix and configuration.
  public static void signToken(
      byte[] base64Key, String signatureAlgorithm, Optional<Instant> startTime,
      Instant expirationTime, Optional<String> urlPrefix, Optional<String> fullPath,
      Optional<String> pathGlobs, Optional<String> sessionId, Optional<String> data,
      Optional<List<Header>> headers, Optional<String> ipRanges)
      throws NoSuchAlgorithmException, InvalidKeyException {

    String field = "";
    byte[] decodedKey = Base64.getUrlDecoder().decode(base64Key);

    // For most fields, the value in the token and the value to sign
    // are the same. Compared to the token, the FullPath and Headers
    // use a different string for the value to sign. To illustrate this difference,
    // we'll keep the token and the value to be signed separate.
    List<String> tokens = new ArrayList<>();
    List<String> toSign = new ArrayList<>();

    // Check for `fullPath` or `pathGlobs` or `urlPrefix`.
    if (fullPath.isPresent()) {
      tokens.add("FullPath");
      toSign.add(String.format("FullPath=%s", fullPath.get()));
    } else if (pathGlobs.isPresent()) {
      field = String.format("PathGlobs=%s", pathGlobs.get().trim());
      tokens.add(field);
      toSign.add(field);
    } else if (urlPrefix.isPresent()) {
      field = String.format("URLPrefix=%s",
          base64Encoder(urlPrefix.get().getBytes(StandardCharsets.UTF_8)));
      tokens.add(field);
      toSign.add(field);
    } else {
      throw new IllegalArgumentException(
          "User Input Missing: One of `urlPrefix`, `fullPath` or `pathGlobs` must be specified");
    }

    // Check & parse optional params.
    long epochDuration;
    if (startTime.isPresent()) {
      epochDuration = ChronoUnit.SECONDS.between(Instant.EPOCH, startTime.get());
      field = String.format("Starts=%s", epochDuration);
      tokens.add(field);
      toSign.add(field);
    }

    if (expirationTime == null) {
      expirationTime = Instant.now().plus(1, ChronoUnit.HOURS);
    }
    epochDuration = ChronoUnit.SECONDS.between(Instant.EPOCH, expirationTime);
    field = String.format("Expires=%s", epochDuration);
    tokens.add(field);
    toSign.add(field);

    if (sessionId.isPresent()) {
      field = String.format("SessionID=%s", sessionId.get());
      tokens.add(field);
      toSign.add(field);
    }

    if (data.isPresent()) {
      field = String.format("Data=%s", data.get());
      tokens.add(field);
      toSign.add(field);
    }

    if (headers.isPresent()) {
      List<String> headerNames = new ArrayList<>();
      List<String> headerPairs = new ArrayList<>();

      for (Header entry : headers.get()) {
        headerNames.add(entry.getName());
        headerPairs.add(String.format("%s=%s", entry.getName(), entry.getValue()));
      }
      tokens.add(String.format("Headers=%s", String.join(",", headerNames)));
      toSign.add(String.format("Headers=%s", String.join(",", headerPairs)));
    }

    if (ipRanges.isPresent()) {
      field = String.format("IPRanges=%s",
          base64Encoder(ipRanges.get().getBytes(StandardCharsets.US_ASCII)));
      tokens.add(field);
      toSign.add(field);
    }

    // Generate token.
    String toSignJoined = String.join("~", toSign);
    byte[] toSignBytes = toSignJoined.getBytes(StandardCharsets.UTF_8);
    String algorithm = signatureAlgorithm.toLowerCase();

    if (algorithm.equalsIgnoreCase("ed25519")) {
      Ed25519PrivateKeyParameters privateKey = new Ed25519PrivateKeyParameters(decodedKey, 0);
      Ed25519Signer signer = new Ed25519Signer();
      signer.init(true, privateKey);
      signer.update(toSignBytes, 0, toSignBytes.length);
      byte[] signature = signer.generateSignature();
      tokens.add(String.format("Signature=%s", base64Encoder(signature)));
    } else if (algorithm.equalsIgnoreCase("sha256")) {
      String sha256 = "HmacSHA256";
      Mac mac = Mac.getInstance(sha256);
      SecretKeySpec secretKeySpec = new SecretKeySpec(decodedKey, sha256);
      mac.init(secretKeySpec);
      byte[] signature = mac.doFinal(toSignBytes);
      tokens.add(String.format("hmac=%s", Hex.toHexString(signature)));
    } else if (algorithm.equalsIgnoreCase("sha1")) {
      String sha1 = "HmacSHA1";
      Mac mac = Mac.getInstance(sha1);
      SecretKeySpec secretKeySpec = new SecretKeySpec(decodedKey, sha1);
      mac.init(secretKeySpec);
      byte[] signature = mac.doFinal(toSignBytes);
      tokens.add(String.format("hmac=%s", Hex.toHexString(signature)));
    } else {
      throw new Error(
          "Input Missing Error: `signatureAlgorithm` can only be one of `sha1`, `sha256` or "
              + "`ed25519`");
    }
    // The signed URL appended with the query parameters based on the
    // specified URL prefix and configuration.
    System.out.println(String.join("~", tokens));
  }

  // Returns a base64-encoded string compatible with Media CDN.
  // Media CDN uses URL-safe base64 encoding and strips off the padding at the
  // end.
  public static String base64Encoder(byte[] value) {
    byte[] encodedBytes = Base64.getUrlEncoder().withoutPadding().encode(value);
    return new String(encodedBytes, StandardCharsets.UTF_8);
  }

  public static class Header {

    private String name;
    private String value;

    public Header(String name, String value) {
      this.name = name;
      this.value = value;
    }

    public String getName() {
      return name;
    }

    public void setName(String name) {
      this.name = name;
    }

    public String getValue() {
      return value;
    }

    public void setValue(String value) {
      this.value = value;
    }

    @Override
    public String toString() {
      return "Header{"
          + "name='" + name + '\''
          + ", value='" + value + '\''
          + '}';
    }
  }

}

以下部分介绍了令牌使用的字段。

必需的令牌字段

对于每个令牌,以下字段都是必填字段:

  • Expires
  • 以下任意一项:
    • PathGlobs
    • URLPrefix
    • FullPath
  • 以下任意一项:
    • Signature
    • hmac

除非另有说明,否则参数名称及其值区分大小写。

下表介绍了各个参数:

字段名称 / 别名 令牌参数 有符号值

Expires

exp

自 Unix 纪元 (1970-01-01T00:00:00Z) 起经过的整数秒数 Expires=EXPIRATION_TIME,之后令牌将失效。

PathGlobs

pathsacl

要授予访问权限的路径段的列表(最多五个)。这些段可以使用英文逗号 (,) 或感叹号 (!) 分隔,但不能同时使用两者分隔。

PathGlobs 支持使用星号 (*) 和问号 (?) 在路径中使用通配符。单个星号 (*) 字符可跨越任意数量的路径段,这与 pathMatchTemplate 的模式匹配语法不同。

不允许使用以英文分号 (;) 表示的路径参数,因为它们会在匹配时产生歧义。

出于上述原因,请确保您的网址不包含以下特殊字符:,!*?;

PathGlobs=PATHS
URLPrefix

一个可在网络中安全使用的 base64 编码网址,其中包含 http://https:// 协议,直至达到您所选的位置。

例如,“https://example.com/foo/bar.ts”的一些有效 网址Prefix 值包括“https://example.com”“https://example.com/foo”和“https://example.com/foo/bar”。

URLPrefix=BASE_64_URL_PREFIX
FullPath 无。在令牌中指定 FullPath 时,不要复制在签名值中指定的路径。在令牌中,包含字段名称但不带 = FullPath=FULL_PATH_TO_OBJECT
Signature 网络安全的 base64 编码版本的签名。 不适用
hmac HMAC 值的 Web 安全 base64 编码版本。 不适用

PathGlobs 通配符语法

下表介绍了 PathGlobs 通配符语法。

运算符 Matches 示例
*(星号) 匹配网址路径中的零个或多个字符,包括正斜杠 (/) 字符。
  • /videos/* 匹配以 /videos/ 开头的任何路径。
  • /videos/s*/4k/*/videos/s/4k//videos/s01/4k/main.m3u8 匹配。
  • /manifests/*/4k/*/manifests/s01/4k/main.m3u8/manifests/s01/e01/4k/main.m3u8 匹配。它与 /manifests/4k/main.m3u8 不匹配。
?(问号) 匹配网址路径中的单个字符,不包括正斜杠 (/) 字符。 /videos/s?main.m3u8/videos/s1main.m3u8 匹配。它与 /videos/s01main.m3u8/videos/s/main.m3u8 中的任何一个都不匹配。

对于网址路径,glob 必须以星号 (*) 或正斜杠 (/) 开头。

由于 */* 会匹配所有网址路径,因此我们不建议在签名令牌中使用这两者。为了最大限度提供保护,请确保您的 glob 与您打算授予访问权限的内容相匹配。

可选令牌字段

除非另有说明,否则参数名称及其值区分大小写。

下表介绍了参数名称、任何别名和可选参数的详细信息:

字段名称 / 别名 参数 有符号值

Starts

st

自 Unix 纪元 (1970-01-01T00:00:00Z) 以来的整数秒数 Starts=START_TIME
IPRanges

一个 CIDR 格式的 IPv4 和 IPv6 地址列表(最多五个),此网址采用可保障网络安全的 base64 格式。例如,如需指定 IP 范围“192.6.13.13/32,193.5.64.135/32”,您可以指定 IPRanges=MTkyLjYuMTMuMTMvMzIsMTkzLjUuNjQuMTM1LzMy

当客户端面临 WAN 迁移风险或应用前端的网络路径与传送路径不同时,在令牌中添加 IP 地址范围可能没有帮助。如果客户端所连接 IP 地址不属于签名请求,则媒体 CDN 会拒绝包含 HTTP 403 代码的客户端。

以下情况可能会导致媒体 CDN 拒绝包含 HTTP 403 代码的客户端:

  • 双栈(IPv4、IPv6)环境
  • 连接迁移(从 Wi-Fi 到移动网络,以及从移动网络到 Wi-Fi)
  • 使用运营商网关 NAT(CGNAT 或 CGN)的移动网络
  • 多路径 TCP (MPTCP)

所有这些因素都会导致给定客户端在视频播放会话期间具有不确定的 IP 地址。如果客户端 IP 地址在您授予访问权限后发生更改,而客户端尝试随后将视频片段下载到其播放缓冲区,则它们会从媒体 CDN 收到 HTTP 403

IPRanges=BASE_64_IP_RANGES

SessionID

id

任意字符串,适用于日志分析或回放跟踪。

为避免创建无效令牌,请使用 % 编码或网络安全 base64 编码的字符串。不得对 SessionID 使用以下字符,因为这会导致令牌无效:“~”“&”或“ ”(空格)。

SessionID=SESSION_ID_VALUE

Data

datapayload

任意字符串,适用于日志分析。

为避免创建无效令牌,请使用 % 编码或网络安全 base64 编码的字符串。不得对 Data 使用以下字符,因为这会导致令牌无效:“~”“&”或“ ”(空格)。

data=DATA_VALUE
Headers 以英文逗号分隔的标头字段名称列表。对于请求中的查找,标头名称不区分大小写。签名值中的标头名称区分大小写。如果缺少标头,则该值为空字符串。如果标头有多个副本,这些副本会用英文逗号分隔。 Headers=HEADER_1_NAME=HEADER_1_EXPECTED_VALUE, HEADER_2_NAME=HEADER_2_EXPECTED_VALUE

示例

以下部分展示了生成令牌的示例。

使用 FullPath 的示例

请参考以下示例(使用 FullPath 字段):

  • 所请求的项:http://example.com/tv/my-show/s01/e01/playlist.m3u8
  • 到期时间:160000000

带符号的值为:

Expires=160000000~FullPath=/tv/my-show/s01/e01/playlist.m3u8

如需创建令牌,请使用 Ed25519 签名或对称密钥 HMAC 对已签名的值进行签名。

以下是根据有符号值创建的示例令牌:

Ed25519 签名

Expires=160000000~FullPath~Signature=SIGNATURE_OF_SIGNED_VALUE

其中 SIGNATURE_OF_SIGNED_VALUE 是之前创建的签名值的 ED25519 签名。

对称密钥 HMAC

Expires=160000000~FullPath~hmac=HMAC_OF_SIGNED_VALUE

其中 HMAC_OF_SIGNED_VALUE 是之前创建的签名值的对称密钥 HMAC。

在前面的示例中,令牌中提供了 FullPath,但签名值中指定的路径没有重复值。这样,您就可以对请求的完整路径进行签名,而无需在令牌中复制请求。

使用 URLPrefix 的示例

请参考以下示例(使用 URLPrefix 字段):

  • 所请求的项:http://example.com/tv/my-show/s01/e01/playlist.m3u8
  • 到期时间:160000000

带符号的值为:

Expires=160000000~URLPrefix=aHR0cDovL2V4YW1wbGUuY29tL3R2L215LXNob3cvczAxL2UwMS9wbGF5bGlzdC5tM3U4

在前面的示例中,我们将所请求项的路径 http://example.com/tv/my-show/s01/e01/playlist.m3u8 替换为该项路径(采用网络安全 Base64 格式 aHR0cDovL2V4YW1wbGUuY29tL3R2L215LXNob3cvczAxL2UwMS9wbGF5bGlzdC5tM3U4)。

如需创建令牌,请使用 Ed25519 签名或对称密钥 HMAC 对已签名的值进行签名。

以下是根据有符号值创建的示例令牌:

Ed25519 签名

Expires=160000000~URLPrefix=aHR0cDovL2V4YW1wbGUuY29tL3R2L215LXNob3cvczAxL2UwMS9wbGF5bGlzdC5tM3U4~Signature=SIGNATURE_OF_SIGNED_VALUE

其中 SIGNATURE_OF_SIGNED_VALUE 是之前创建的签名值的 ED25519 签名。

对称密钥 HMAC

Expires=160000000~URLPrefix=aHR0cDovL2V4YW1wbGUuY29tL3R2L215LXNob3cvczAxL2UwMS9wbGF5bGlzdC5tM3U4~hmac=HMAC_OF_SIGNED_VALUE

其中 HMAC_OF_SIGNED_VALUE 是之前创建的签名值的对称密钥 HMAC。

使用 Headers 的示例

请参考以下示例(使用 Headers 字段):

  • 所请求的项:http://example.com/tv/my-show/s01/e01/playlist.m3u8
  • 到期时间:160000000
  • PathGlobs 值:*
  • 预期的请求标头:
    • user-agent: browser
    • accept: text/html

带符号的值为:

Expires=160000000~PathGlobs=*~Headers=user-agent=browser,accept=text/html

如需创建令牌,请使用 Ed25519 签名或对称密钥 HMAC 对已签名的值进行签名。

以下是根据有符号值创建的示例令牌:

Ed25519 签名

Expires=160000000~PathGlobs=*~Headers=user-agent,accept~Signature=SIGNATURE_OF_SIGNED_VALUE

其中 SIGNATURE_OF_SIGNED_VALUE 是之前创建的签名值的 ED25519 签名。

对称密钥 HMAC

Expires=160000000~PathGlobs=*~Headers=user-agent,accept~hmac=HMAC_OF_SIGNED_VALUE

其中 HMAC_OF_SIGNED_VALUE 是之前创建的签名值的对称密钥 HMAC。

在前面的示例中,令牌中提供了 Headers=user-agent,accept,但预期的标头值并没有从签名值中重复。这样,您就可以对特定的请求标头键值对进行签名,而无需复制令牌中的值。