在demaind上,Azure Media Services视频的JWT令牌解密失败

时间:2018-03-26 17:22:54

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

详情

  • 播放器无法解密流。
  • 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;
}

1 个答案:

答案 0 :(得分:1)

对于其他人,可能遇到过这个问题。它解决了:

  1. 问题网址需要尾随斜杠
  2. 添加了urn:microsoft:azure:mediaservices:contentkeyidentifier
  3. 使用Azure Media Explorer搞清楚。