You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET C#站点动态生成Azure V3令牌实现高级CDN认证的API/工具咨询

在ASP.NET C#中生成Azure CDN V3认证令牌的方案

核心实现思路

Azure CDN V3令牌认证基于HMAC-SHA256签名机制,无需依赖第三方工具,用.NET原生类库就能完成令牌生成,灵活可控且性能可靠。

手动实现签名(推荐方案)

以下是可直接复用的C#代码,包含生成V3令牌的完整逻辑:

using System;
using System.Security.Cryptography;
using System.Text;
using System.Web;

public static class CdnTokenGenerator
{
    public static string GenerateV3Token(string cdnAuthKey, string resourcePath, DateTime expires, string allowedIpRange = null, string protocol = null)
    {
        // 1. 构造签名参数
        var paramBuilder = new StringBuilder();
        paramBuilder.Append($"url={HttpUtility.UrlEncode(resourcePath)}");
        paramBuilder.Append($"&expires={ToUnixTimeSeconds(expires)}");

        if (!string.IsNullOrWhiteSpace(allowedIpRange))
        {
            paramBuilder.Append($"&ip={HttpUtility.UrlEncode(allowedIpRange)}");
        }

        if (!string.IsNullOrWhiteSpace(protocol))
        {
            paramBuilder.Append($"&protocol={HttpUtility.UrlEncode(protocol)}");
        }

        // 2. HMAC-SHA256签名
        var keyBytes = Encoding.UTF8.GetBytes(cdnAuthKey);
        using var hmac = new HMACSHA256(keyBytes);
        var paramBytes = Encoding.UTF8.GetBytes(paramBuilder.ToString());
        var signatureBytes = hmac.ComputeHash(paramBytes);
        var encodedSignature = HttpUtility.UrlEncode(Convert.ToBase64String(signatureBytes));

        // 3. 组合最终令牌
        return $"?{paramBuilder.ToString()}&signature={encodedSignature}";
    }

    private static long ToUnixTimeSeconds(DateTime dateTime)
    {
        return new DateTimeOffset(dateTime).ToUnixTimeSeconds();
    }
}

使用示例

在ASP.NET业务逻辑或控制器中调用:

// 从配置读取CDN密钥(禁止硬编码,建议用Azure Key Vault或加密配置)
var cdnKey = Configuration["CdnSettings:AuthKey"];
// 需保护的CDN资源路径(如"/media/hd-video.mp4")
var targetResource = "/your-cdn-resource-path";
// 令牌过期时间(示例为1小时后)
var expireTime = DateTime.UtcNow.AddHours(1);
// 可选:限制访问IP段
var allowedIp = "10.0.0.0/24";

var authToken = CdnTokenGenerator.GenerateV3Token(cdnKey, targetResource, expireTime, allowedIp);
// 最终可访问的带令牌URL:https://your-cdn-domain.com/your-cdn-resource-path?url=...&expires=...&signature=...

关键注意事项

  • 密钥安全:CDN认证密钥必须加密存储,避免硬编码或明文暴露。
  • 参数编码:所有参数值必须经过URL编码,防止特殊字符导致签名验证失败。
  • 时间同步:确保服务器时间与UTC时间同步,否则过期时间校验会出现异常。

内容的提问来源于stack exchange,提问作者N.D.B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 09:45:33