【问题标题】:JWT token decryption fails wit Azure Media Services video on demaindJWT 令牌解密失败,Azure 媒体服务视频点播
【发布时间】:2018-03-26 17:22:53
【问题描述】:

详情

  • 播放器无法解密流。
  • JWT 令牌使用有效证书进行签名。
  • 测试令牌签名工作 - 使用示例代码。
  • 代码如下

问题

  • JWT 应包含哪些声明?文档中提到 JWT 声明应符合限制条件,但未指定是否应包含任何声明。
  • 是否有任何使用自定义 STS/JWT 令牌的示例?我查看了大部分我能找到的在线示例。

https://github.com/AzureMediaServicesSamples/AES-Key-Delivery-with-ACS/blob/master/ConsoleApplication6/Program.cs

http://gtrifonov.com/2015/01/03/jwt-token-authentication-in-azure-media-services-and-dynamic-encryption/

https://azure.microsoft.com/en-us/resources/samples/?service=media-services&sort=0

// Code start

public static X509Certificate2 SigningCertificate => new X509Certificate2(Path.Combine(Config.BaseSurRoot, Config.AzureStreaming.CertificateFileName), Config.AzureStreaming.CertificatePassword);

private string GenerateJwtToken(int durationMs)
{
    var now = DateTime.UtcNow;
    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(new Claim[]
                {
                    //new Claim(ClaimTypes.Name, Name),
                    //new Claim(ClaimTypes.Role, "Play"),
                }),
        TokenIssuerName = Config.AzureStreaming.Issuer,
        AppliesToAddress = Config.AzureStreaming.Audience,
        Lifetime = new Lifetime(now, now.AddMilliseconds(durationMs)),
        SigningCredentials = new X509SigningCredentials(Azure.SigningCertificate)
    };

    var tokenHandler = new JwtSecurityTokenHandler();
    var token = tokenHandler.CreateToken(tokenDescriptor);
    var tokenString = tokenHandler.WriteToken(token);

    return "Bearer=" + tokenString;
}

private static ContentKeyAuthorizationPolicyRestriction GetJwtTokenRestriction()
{
    var template = new TokenRestrictionTemplate(TokenType.JWT)
    {
        PrimaryVerificationKey = new X509CertTokenVerificationKey(Azure.SigningCertificate),
        Audience = new Uri(Config.AzureStreaming.Audience).ToString(),
        Issuer = new Uri(Config.AzureStreaming.Issuer).ToString()
    };

    return new ContentKeyAuthorizationPolicyRestriction
    {
        Name = "Jwt Token Restriction",
        KeyRestrictionType = (int)ContentKeyRestrictionType.TokenRestricted,
        Requirements = TokenRestrictionTemplateSerializer.Serialize(template),
    };
}

private static IContentKey CreateEnvelopeTypeContentKey(this IAsset asset)
{
    // Create envelope encryption content key
    var keyId = Guid.NewGuid();
    byte[] contentKey = GetRandomBuffer(16);

    var key = AzureContext.ContentKeys.Create(
                            keyId,
                            contentKey,
                            "ContentKey",
                            ContentKeyType.EnvelopeEncryption);

    // Associate the key with the asset.
    asset.ContentKeys.Add(key);

    return key;
}

private static void AddTokenRestrictedPolicy(this IContentKey contentKey, ContentKeyAuthorizationPolicyRestriction requirement, bool testMode)
{
    var prefix = testMode ? "Test" : "Jwt";
    var policy = AzureContext.ContentKeyAuthorizationPolicies.CreateAsync($"{prefix} Token Policy").Result;
    policy.Options.Add(AzureContext.ContentKeyAuthorizationPolicyOptions.Create(
            $"{prefix} Token Policy Option",
            ContentKeyDeliveryType.BaselineHttp,
            new List<ContentKeyAuthorizationPolicyRestriction> { requirement, },
            null)  // no key delivery data is needed for HLS
    );

    contentKey.AuthorizationPolicyId = policy.Id;
    var updatedKey = contentKey.UpdateAsync().Result;
    Log.Info("Adding Key to Asset: Key ID is " + updatedKey.Id);
}

private static void CreateAssetDeliveryPolicy(this IAsset asset, IContentKey key)
{
    var keyAcquisitionUri = key.GetKeyDeliveryUrl(ContentKeyDeliveryType.BaselineHttp);

    var envelopeEncryptionIV = Convert.ToBase64String(GetRandomBuffer(16));

    // The following policy configuration specifies:
    //   key url that will have KID=<Guid> appended to the envelope and
    //   the Initialization Vector (IV) to use for the envelope encryption.
    var assetDeliveryPolicyConfiguration = new Dictionary<AssetDeliveryPolicyConfigurationKey, string>
        {
            {AssetDeliveryPolicyConfigurationKey.EnvelopeKeyAcquisitionUrl, keyAcquisitionUri.ToString()}
        };

    var assetDeliveryPolicy = AzureContext.AssetDeliveryPolicies.Create(
                    "AssetDeliveryPolicy",
                    AssetDeliveryPolicyType.DynamicEnvelopeEncryption,
                    AssetDeliveryProtocol.SmoothStreaming | AssetDeliveryProtocol.HLS | AssetDeliveryProtocol.Dash,
                    assetDeliveryPolicyConfiguration);

    asset.DeliveryPolicies.Add(assetDeliveryPolicy);
    Log.Info("Adding Asset Delivery Policy: " + assetDeliveryPolicy.AssetDeliveryPolicyType);
}

private static string GetStreamingOriginLocator(this IAsset asset, int days = 30)
{
    // Get a reference to the streaming manifest file
    var assetFile = asset.AssetFiles.Where(f => f.Name.ToLower().EndsWith(".ism")).FirstOrDefault();

    var policy = AzureContext.AccessPolicies.Create("Streaming policy", TimeSpan.FromDays(30), AccessPermissions.Read);

    var originLocator = AzureContext.Locators.CreateLocator(LocatorType.OnDemandOrigin, asset, policy, DateTime.UtcNow.AddMinutes(-5));

    // Create a URL to the manifest file.
    return originLocator.Path + assetFile.Name;
}

【问题讨论】:

    标签: azure video-streaming jwt azure-media-services


    【解决方案1】:

    对于可能遇到此问题的其他人。已通过以下方式解决:

    1. 问题 url 需要尾部斜杠
    2. 添加了 urn:microsoft:azure:mediaservices:contentkeyidentifier

    使用 Azure 媒体资源管理器找出答案。

    【讨论】:

      猜你喜欢
      • 2015-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多