예제 #1
0
        public static void ClassInit(TestContext context)
        {
            //CreateCounters();

            _mediaContext = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext();
            IContentKeyAuthorizationPolicyOption policyOption = null;

            for (int i = 0; i < 10; i++)
            {
                byte[]      expectedKey = null;
                IContentKey contentKey  = GetKeyDeliveryUrlTests.CreateTestKey(_mediaContext, ContentKeyType.EnvelopeEncryption, out expectedKey);

                policyOption = ContentKeyAuthorizationPolicyOptionTests.CreateOption(_mediaContext, String.Empty, ContentKeyDeliveryType.BaselineHttp, null, null, ContentKeyRestrictionType.Open);

                List <IContentKeyAuthorizationPolicyOption> options = new List <IContentKeyAuthorizationPolicyOption>
                {
                    policyOption
                };

                GetKeyDeliveryUrlTests.CreateTestPolicy(_mediaContext, String.Empty, options, ref contentKey);

                Uri keyDeliveryServiceUri = contentKey.GetKeyDeliveryUrl(ContentKeyDeliveryType.BaselineHttp);

                Assert.IsNotNull(keyDeliveryServiceUri);
                string rawkey = EncryptionUtils.GetKeyIdAsGuid(contentKey.Id).ToString();
                _testData.Add(new Tuple <Uri, string, string>(keyDeliveryServiceUri, TokenServiceClient.GetAuthTokenForKey(rawkey), GetKeyDeliveryUrlTests.GetString(expectedKey)));
            }
        }
예제 #2
0
        public void GetPlayReadyLicenseDeliveryUrl()
        {
            IContentKey contentKey = null;
            IContentKeyAuthorizationPolicy       contentKeyAuthorizationPolicy = null;
            IContentKeyAuthorizationPolicyOption policyOption = null;

            try
            {
                contentKey = CreateTestKey(_mediaContext, ContentKeyType.CommonEncryption);

                PlayReadyLicenseResponseTemplate responseTemplate = new PlayReadyLicenseResponseTemplate();
                responseTemplate.LicenseTemplates.Add(new PlayReadyLicenseTemplate());
                string licenseTemplate = MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);

                policyOption = ContentKeyAuthorizationPolicyOptionTests.CreateOption(_mediaContext, String.Empty, ContentKeyDeliveryType.PlayReadyLicense, null, licenseTemplate, ContentKeyRestrictionType.Open);

                List <IContentKeyAuthorizationPolicyOption> options = new List <IContentKeyAuthorizationPolicyOption>
                {
                    policyOption
                };

                contentKeyAuthorizationPolicy = CreateTestPolicy(_mediaContext, String.Empty, options, ref contentKey);

                Uri keyDeliveryServiceUri = contentKey.GetKeyDeliveryUrl(ContentKeyDeliveryType.PlayReadyLicense);

                Assert.IsNotNull(keyDeliveryServiceUri);
                Assert.IsTrue(0 == String.Compare(keyDeliveryServiceUri.AbsolutePath, "/PlayReady/", StringComparison.OrdinalIgnoreCase));
            }
            finally
            {
                CleanupKeyAndPolicy(contentKey, contentKeyAuthorizationPolicy, policyOption);
            }
        }
예제 #3
0
        //given an unprotected IAsset, set up dynamic PR protection
        //you have to publish AFTER this setup
        public static void SetupDynamicPlayReadyProtection(CloudMediaContext objCloudMediaContext, IAsset objIAsset)
        {
            string keySeedB64, contentKeyB64;
            Guid   keyId = Guid.NewGuid();

            //Different ways to create content key:
            //Method 1: Without using key seed, generete content key directly
            //contentKeyB64 = GeneratePlayReadyContentKey();
            //Method 2: With a given key seed and generated key ID (Key Identifiers are unique in the system and there can only be one key with a given Guid within a cluster (even across accounts for now although that may change to be account scoped in the future).  If you try to submit a protection job with a keyId that already exists but a different key value that will cause the PlayReady protection job to fail (the same keyId and keyValue is okay).
            keySeedB64    = "XVBovsmzhP9gRIZxWfFta3VVRPzVEWmJsazEJ46I";
            contentKeyB64 = GetPlayReadyContentKeyFromKeyIdKeySeed(keyId.ToString(), keySeedB64);
            //Method 3: With a randomly generated key seed, create content key from the key ID and key seed
            //keySeedB64 = GeneratePlayReadyKeySeed();
            //contentKeyB64 = GetPlayReadyContentKeyFromKeyIdKeySeed(keyId.ToString(), keySeedB64);
            //Method 4: Reuse an existing key ID
            //keyId = new Guid("a7586184-40ff-4047-9edd-6a8273ac50fc");
            //keySeedB64 = "XVBovsmzhP9gRIZxWfFta3VVRPzVEWmJsazEJ46I";
            //contentKeyB64 = GetPlayReadyContentKeyFromKeyIdKeySeed(keyId.ToString(), keySeedB64);
            Console.WriteLine(string.Format("STEP 1: Key ID = {0}, Content Key = {1}, Key Seed = {2}", contentKeyB64, keyId.ToString(), keySeedB64));

            IContentKey objIContentKey = ConfigureKeyDeliveryService(objCloudMediaContext, keyId, contentKeyB64, objIAsset.Id);

            //associate IAsset with the IContentkey
            objIAsset.ContentKeys.Add(objIContentKey);
            CreateAssetDeliveryPolicy(objCloudMediaContext, objIAsset, objIContentKey);
        }
예제 #4
0
        public void EnsureNoneKeyDeliveryUrlFails()
        {
            IContentKey contentKey = null;
            IContentKeyAuthorizationPolicy       contentKeyAuthorizationPolicy = null;
            IContentKeyAuthorizationPolicyOption policyOption = null;

            try
            {
                contentKey = CreateTestKey(_mediaContext, ContentKeyType.EnvelopeEncryption);

                policyOption = ContentKeyAuthorizationPolicyOptionTests.CreateOption(_mediaContext, String.Empty, ContentKeyDeliveryType.BaselineHttp, null, null, ContentKeyRestrictionType.Open);

                List <IContentKeyAuthorizationPolicyOption> options = new List <IContentKeyAuthorizationPolicyOption>
                {
                    policyOption
                };

                contentKeyAuthorizationPolicy = CreateTestPolicy(_mediaContext, String.Empty, options, ref contentKey);

                Uri keyDeliveryServiceUri = contentKey.GetKeyDeliveryUrl(ContentKeyDeliveryType.None);
            }
            finally
            {
                CleanupKeyAndPolicy(contentKey, contentKeyAuthorizationPolicy, policyOption);
            }
        }
예제 #5
0
        public static IContentKey CreateTestKey(CloudMediaContext mediaContext, ContentKeyType contentKeyType, out byte[] key, string name = "")
        {
            key = ContentKeyTests.GetRandomBuffer(16);
            IContentKey contentKey = mediaContext.ContentKeys.Create(Guid.NewGuid(), key, name, contentKeyType);

            return(contentKey);
        }
예제 #6
0
        public static IContentKey AddAuthorizationPolicyToContentKey(string assetID, CloudMediaContext mediaContext, IContentKey objIContentKey, string claimType, string[] claimValue)
        {
            //we name auth policy same as asset
            var policy = mediaContext.ContentKeyAuthorizationPolicies.Where(c => c.Name == assetID).FirstOrDefault();

            // Create ContentKeyAuthorizationPolicy with restrictions and create authorization policy
            if (policy == null)
            {
                policy = mediaContext.ContentKeyAuthorizationPolicies.CreateAsync(assetID).Result;
            }

            // Add each claim (group) as a Policy Option
            foreach (var claim in claimValue)
            {
                CreatePolicyOption(assetID, mediaContext, claimType, claim, policy);
            }

            // After adding Policy Options to the Policy, update it
            policy.UpdateAsync();


            // Add ContentKeyAutorizationPolicy to ContentKey
            objIContentKey.AuthorizationPolicyId = policy.Id;
            IContentKey IContentKeyUpdated = objIContentKey.UpdateAsync().Result;

            return(IContentKeyUpdated);
        }
예제 #7
0
        private static string DecryptedFile(IIngestManifestFile ingestManifestFile, string encryptedPath, CloudMediaContext context)
        {
            IIngestManifestAsset ingestManifestAsset = context.IngestManifestAssets.Where(a => a.Id == ingestManifestFile.ParentIngestManifestAssetId).FirstOrDefault();

            Assert.IsNotNull(ingestManifestAsset);

            IList <IContentKey> keys = ingestManifestAsset.Asset.ContentKeys.Where(c => c.ContentKeyType == ContentKeyType.StorageEncryption).ToList();

            Assert.AreEqual(1, keys.Count, "Expecting only one storage key per asset");
            IContentKey key = keys.FirstOrDefault();

            Assert.IsNotNull(ingestManifestAsset);


            Guid           keyId          = EncryptionUtils.GetKeyIdAsGuid(key.Id);
            FileEncryption fileEncryption = new FileEncryption(key.GetClearKeyValue(), keyId);

            ulong iv            = Convert.ToUInt64(ingestManifestFile.InitializationVector, CultureInfo.InvariantCulture);
            var   decryptedPath = @".\Resources\TestFiles\Decrypted" + Guid.NewGuid();

            if (!Directory.Exists(decryptedPath))
            {
                Directory.CreateDirectory(decryptedPath);
            }

            decryptedPath = Path.Combine(decryptedPath, ingestManifestFile.Name);
            FileInfo      fileInfo        = new FileInfo(encryptedPath);
            var           maxblocksize    = GetBlockSize(fileInfo.Length);
            List <string> blockList       = new List <string>();
            int           numberOfthreads = 1;
            var           queue           = PreapreDownloadQueue(maxblocksize, fileInfo.Length, ref numberOfthreads, out blockList);

            using (var fs = new FileStream(decryptedPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read))
            {
                KeyValuePair <int, int> block;
                while (queue.TryDequeue(out block))
                {
                    fs.Seek(block.Key * maxblocksize, SeekOrigin.Begin);
                    using (FileStream stream = File.OpenRead(encryptedPath))
                    {
                        byte[] buffer = new byte[block.Value];
                        stream.Seek(block.Key * maxblocksize, SeekOrigin.Begin);
                        int read = stream.Read(buffer, 0, (int)block.Value);
                        if (fileEncryption != null)
                        {
                            lock (fileEncryption)
                            {
                                using (FileEncryptionTransform encryptor = fileEncryption.GetTransform(iv, block.Key * maxblocksize))
                                {
                                    encryptor.TransformBlock(inputBuffer: buffer, inputOffset: 0, inputCount: buffer.Length, outputBuffer: buffer, outputOffset: 0);
                                }
                            }
                        }

                        fs.Write(buffer, 0, buffer.Length);
                    }
                }
            }
            return(decryptedPath);
        }
예제 #8
0
        public void EnsureEnvelopeKeyDeliveryUrlForCommonKeyFails()
        {
            IContentKey contentKey = null;
            IContentKeyAuthorizationPolicy       contentKeyAuthorizationPolicy = null;
            IContentKeyAuthorizationPolicyOption policyOption = null;

            PlayReadyLicenseResponseTemplate responseTemplate = new PlayReadyLicenseResponseTemplate();

            responseTemplate.LicenseTemplates.Add(new PlayReadyLicenseTemplate());
            string licenseTemplate = MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);

            try
            {
                contentKey = CreateTestKey(_mediaContext, ContentKeyType.CommonEncryption);

                policyOption = ContentKeyAuthorizationPolicyOptionTests.CreateOption(_mediaContext, String.Empty, ContentKeyDeliveryType.PlayReadyLicense, null, licenseTemplate, ContentKeyRestrictionType.Open);

                List <IContentKeyAuthorizationPolicyOption> options = new List <IContentKeyAuthorizationPolicyOption>
                {
                    policyOption
                };

                contentKeyAuthorizationPolicy = CreateTestPolicy(_mediaContext, String.Empty, options, ref contentKey);

                Uri keyDeliveryServiceUri = contentKey.GetKeyDeliveryUrl(ContentKeyDeliveryType.BaselineHttp);
            }
            finally
            {
                CleanupKeyAndPolicy(contentKey, contentKeyAuthorizationPolicy, policyOption);
            }
        }
        private static string AddFairPlayTokenRestrictedAuthorizationPolicyFairPlay(IContentKey contentKey)
        {
            string tokenTemplateString = DRMHelper.GenerateTokenRequirementsString(_tokenPrimaryVerificationKey, _tokenAlternativeVerificationKey, _tokenScope, _tokenIssuer, true);

            List <ContentKeyAuthorizationPolicyRestriction> restrictions = new List <ContentKeyAuthorizationPolicyRestriction>
            {
                new ContentKeyAuthorizationPolicyRestriction
                {
                    Name = "FairPlay Token Authorization Policy",
                    KeyRestrictionType = (int)ContentKeyRestrictionType.TokenRestricted,
                    Requirements       = tokenTemplateString,
                }
            };

            // Configure FairPlay policy option.
            string FairPlayConfiguration = ConfigureFairPlayPolicyOptions();

            IContentKeyAuthorizationPolicyOption FairPlayPolicy = _context.ContentKeyAuthorizationPolicyOptions.Create("FairPlay token option", ContentKeyDeliveryType.FairPlay, restrictions, FairPlayConfiguration);
            IContentKeyAuthorizationPolicy       contentKeyAuthorizationPolicy = _context.ContentKeyAuthorizationPolicies.CreateAsync("Deliver CBC Content Key with token restrictions").Result;

            contentKeyAuthorizationPolicy.Options.Add(FairPlayPolicy);

            // Associate the content key authorization policy with the content key
            contentKey.AuthorizationPolicyId = contentKeyAuthorizationPolicy.Id;
            contentKey = contentKey.UpdateAsync().Result;

            return(tokenTemplateString);
        }
        public void ShouldCreateAssetFileArrayWithPlayReadyEncryption()
        {
            // Note that these files are not really PlayReady encrypted.  For the purposes of this test that is okay.
            IAsset        asset      = _mediaContext.Assets.Create(Guid.NewGuid().ToString(), AssetCreationOptions.CommonEncryptionProtected);
            IAccessPolicy policy     = _mediaContext.AccessPolicies.Create("Write", TimeSpan.FromMinutes(5), AccessPermissions.Write);
            ILocator      locator    = _mediaContext.Locators.CreateSasLocator(asset, policy);
            var           blobclient = new BlobTransferClient
            {
                NumberOfConcurrentTransfers = 5,
                ParallelTransferThreadCount = 5
            };


            foreach (string filePath in new[] { WindowsAzureMediaServicesTestConfiguration.SmallWmv, WindowsAzureMediaServicesTestConfiguration.SmallWmv2 })
            {
                var        info = new FileInfo(filePath);
                IAssetFile file = asset.AssetFiles.Create(info.Name);
                file.UploadAsync(filePath, blobclient, locator, CancellationToken.None).Wait();
            }

            Guid keyId = Guid.NewGuid();

            byte[] contentKey = GetRandomBuffer(16);

            IContentKey key = _mediaContext.ContentKeys.Create(keyId, contentKey);

            asset.ContentKeys.Add(key);

            Assert.IsNotNull(asset, "Asset should be non null");
            Assert.AreNotEqual(Guid.Empty, asset.Id, "Asset ID should not be null");
            Assert.IsTrue(asset.Options == AssetCreationOptions.CommonEncryptionProtected, "AssetCreationOptions did not have the expected value");

            VerifyFileAndContentKeyMetadataForCommonEncryption(asset);
            VerifyContentKeyVersusExpectedValue2(asset, contentKey, keyId);
        }
        static public void CreateAssetDeliveryPolicy(IAsset asset, IContentKey key)
        {
            // Get the PlayReady license service URL.
            Uri acquisitionUrl = key.GetKeyDeliveryUrl(ContentKeyDeliveryType.PlayReadyLicense);

            // GetKeyDeliveryUrl for Widevine attaches the KID to the URL.
            // For example: https://amsaccount1.keydelivery.mediaservices.windows.net/Widevine/?KID=268a6dcb-18c8-4648-8c95-f46429e4927c.
            // The WidevineBaseLicenseAcquisitionUrl (used below) also tells Dynamaic Encryption
            // to append /? KID =< keyId > to the end of the url when creating the manifest.
            // As a result Widevine license aquisition URL will have KID appended twice,
            // so we need to remove the KID that in the URL when we call GetKeyDeliveryUrl.

            Uri        widevineUrl = key.GetKeyDeliveryUrl(ContentKeyDeliveryType.Widevine);
            UriBuilder uriBuilder  = new UriBuilder(widevineUrl);

            uriBuilder.Query = String.Empty;
            widevineUrl      = uriBuilder.Uri;

            Dictionary <AssetDeliveryPolicyConfigurationKey, string> assetDeliveryPolicyConfiguration =
                new Dictionary <AssetDeliveryPolicyConfigurationKey, string>
            {
                { AssetDeliveryPolicyConfigurationKey.PlayReadyLicenseAcquisitionUrl, acquisitionUrl.ToString() },
                { AssetDeliveryPolicyConfigurationKey.WidevineBaseLicenseAcquisitionUrl, widevineUrl.ToString() }
            };

            var assetDeliveryPolicy = _context.AssetDeliveryPolicies.Create(
                "AssetDeliveryPolicy",
                AssetDeliveryPolicyType.DynamicCommonEncryption,
                AssetDeliveryProtocol.Dash,
                assetDeliveryPolicyConfiguration);


            // Add AssetDelivery Policy to the asset
            asset.DeliveryPolicies.Add(assetDeliveryPolicy);
        }
        static public void CreateAssetDeliveryPolicyCencCbcs(IAsset asset, IContentKey key)
        {
            var kdPolicy = _context.ContentKeyAuthorizationPolicies.Where(p => p.Id == key.AuthorizationPolicyId).Single();

            var kdOption = kdPolicy.Options.Single(o => o.KeyDeliveryType == ContentKeyDeliveryType.FairPlay);

            FairPlayConfiguration configFP = JsonConvert.DeserializeObject <FairPlayConfiguration>(kdOption.KeyDeliveryConfiguration);

            // Get the FairPlay license service URL.
            Uri acquisitionUrl = key.GetKeyDeliveryUrl(ContentKeyDeliveryType.FairPlay);

            // The reason the below code replaces "https://" with "skd://" is because
            // in the IOS player sample code which you obtained in Apple developer account,
            // the player only recognizes a Key URL that starts with skd://.
            // However, if you are using a customized player,
            // you can choose whatever protocol you want.
            // For example, "https".

            Dictionary <AssetDeliveryPolicyConfigurationKey, string> assetDeliveryPolicyConfiguration =
                new Dictionary <AssetDeliveryPolicyConfigurationKey, string>
            {
                { AssetDeliveryPolicyConfigurationKey.FairPlayLicenseAcquisitionUrl, acquisitionUrl.ToString().Replace("https://", "skd://") },
                { AssetDeliveryPolicyConfigurationKey.CommonEncryptionIVForCbcs, configFP.ContentEncryptionIV }
            };

            var assetDeliveryPolicy = _context.AssetDeliveryPolicies.Create(
                "AssetDeliveryPolicy CommonEncryptionCbcs (HLS)",
                AssetDeliveryPolicyType.DynamicCommonEncryptionCbcs,
                AssetDeliveryProtocol.HLS,
                assetDeliveryPolicyConfiguration);

            // Add AssetDelivery Policy to the asset
            asset.DeliveryPolicies.Add(assetDeliveryPolicy);
        }
예제 #13
0
        static void Main(string[] args)
        {
            // Create and cache the Media Services credentials in a static class variable.
            _cachedCredentials = new MediaServicesCredentials(
                _mediaServicesAccountName,
                _mediaServicesAccountKey);
            // Used the cached credentials to create CloudMediaContext.
            _context = new CloudMediaContext(_cachedCredentials);

            bool   tokenRestriction    = false;
            string tokenTemplateString = null;


            IContentKey key = CreateCommonTypeContentKey();

            // Print out the key ID and Key in base64 string format
            Console.WriteLine("Created key {0} with key value {1} ", key.Id, System.Convert.ToBase64String(key.GetClearKeyValue()));
            Console.WriteLine("PlayReady License Key delivery URL: {0}", key.GetKeyDeliveryUrl(ContentKeyDeliveryType.PlayReadyLicense));

            if (tokenRestriction)
            {
                tokenTemplateString = AddTokenRestrictedAuthorizationPolicy(key);
            }
            else
            {
                AddOpenAuthorizationPolicy(key);
            }

            Console.WriteLine("Added authorization policy: {0}", key.AuthorizationPolicyId);
            Console.WriteLine();
            Console.ReadLine();
        }
        private static IAssetDeliveryPolicy CreateAssetDeliveryPolicy(IAsset asset, IContentKey key)
        {
            var policy = asset.DeliveryPolicies
                         .Where(p => p.AssetDeliveryProtocol == AssetDeliveryProtocol.HLS)
                         .SingleOrDefault();

            if (policy != null)
            {
                policy.Delete();
            }

            Uri keyUrl = key.GetKeyDeliveryUrl(ContentKeyDeliveryType.Widevine);

            var configuration = new Dictionary <AssetDeliveryPolicyConfigurationKey, string>();

            configuration.Add(AssetDeliveryPolicyConfigurationKey.WidevineLicenseAcquisitionUrl, keyUrl.ToString());

            policy = _mediaContext.AssetDeliveryPolicies.Create(
                "WidevineDeliveryPolicy",
                AssetDeliveryPolicyType.DynamicCommonEncryption,
                AssetDeliveryProtocol.Dash,
                configuration);

            return(policy);
        }
예제 #15
0
        public void TestGetEncryptionState()
        {
            IAsset asset = JobTests.CreateSmoothAsset(_mediaContext, _filePaths, AssetCreationOptions.None);
            AssetDeliveryProtocol protocolsToSet = AssetDeliveryProtocol.HLS | AssetDeliveryProtocol.SmoothStreaming | AssetDeliveryProtocol.Dash;
            Dictionary <AssetDeliveryPolicyConfigurationKey, string> configuration = new Dictionary <AssetDeliveryPolicyConfigurationKey, string>()
            {
                { AssetDeliveryPolicyConfigurationKey.EnvelopeBaseKeyAcquisitionUrl, "https://www.test.com/" },
                { AssetDeliveryPolicyConfigurationKey.EnvelopeEncryptionIVAsBase64, Convert.ToBase64String(ContentKeyTests.GetRandomBuffer(16)) }
            };
            IAssetDeliveryPolicy policy = _mediaContext.AssetDeliveryPolicies.Create("Test Policy", AssetDeliveryPolicyType.DynamicEnvelopeEncryption, protocolsToSet, configuration);
            IContentKey          key    = _mediaContext.ContentKeys.Create(Guid.NewGuid(), ContentKeyTests.GetRandomBuffer(16), "Test key", ContentKeyType.EnvelopeEncryption);

            asset.ContentKeys.Add(key);
            asset.DeliveryPolicies.Add(policy);

            AssetEncryptionState state = asset.GetEncryptionState(protocolsToSet);

            Assert.AreEqual(AssetEncryptionState.DynamicEnvelopeEncryption, state);

            state = asset.GetEncryptionState(AssetDeliveryProtocol.Dash | AssetDeliveryProtocol.Hds);
            Assert.AreEqual(AssetEncryptionState.NoSinglePolicyApplies, state);

            state = asset.GetEncryptionState(AssetDeliveryProtocol.Hds);
            Assert.AreEqual(AssetEncryptionState.BlockedByPolicy, state);

            CleanupAsset(asset);
        }
        static void Main(string[] args)
        {
            VerifyCerts();

            var credentials = new MediaServicesCredentials(_wamsAccount, _wamsAccountKey)
            {
                AcsBaseAddress = _wamsAcsBaseAddress,
                Scope          = _wamsAcsScope
            };

            _mediaContext = new CloudMediaContext(_wamsEndpoint, credentials);

            IAsset asset = CreateAsset();

            IContentKey key = CreateKeyWithPolicy(asset);

            IAssetDeliveryPolicy assetDeliveryPolicy = CreateAssetDeliveryPolicy(asset, key);

            asset.DeliveryPolicies.Add(assetDeliveryPolicy);

            Console.WriteLine("Asset Delivery Policy Added");

            ILocator streamingLocator = CreateLocator(asset);

            IStreamingEndpoint origin = GetOrigin(recreate: false);

            Uri uri = GetManifestUrl(origin, asset, streamingLocator);

            string keyDeliveryUrl = key.GetKeyDeliveryUrl(ContentKeyDeliveryType.FairPlay).ToString();

            Console.WriteLine("ism: {0}\nkey delivery: {1}", uri, keyDeliveryUrl);

            Console.ReadKey();
        }
예제 #17
0
        /// <summary>
        /// Uploads the destinationPath with given path asynchronously
        /// </summary>
        /// <param name="path">The path of a destinationPath to upload</param>
        /// <param name="blobTransferClient">The <see cref="BlobTransferClient"/> which is used to upload files.</param>
        /// <param name="locator">An asset <see cref="ILocator"/> which defines permissions associated with the Asset.</param>
        /// <param name="token">A <see cref="CancellationToken"/> to use for canceling upload operation.</param>
        /// <returns>A function delegate that returns the future result to be available through the Task.</returns>
        public Task UploadAsync(string path, BlobTransferClient blobTransferClient, ILocator locator, CancellationToken token)
        {
            if (blobTransferClient == null)
            {
                throw new ArgumentNullException("blobTransferClient");
            }

            if (locator == null)
            {
                throw new ArgumentNullException("locator");
            }

            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            if (!File.Exists(path))
            {
                throw new FileNotFoundException(path);
            }

            ValidateFileName(path);

            IContentKey          contentKeyData       = null;
            FileEncryption       fileEncryption       = null;
            AssetCreationOptions assetCreationOptions = this.Asset.Options;

            if (assetCreationOptions.HasFlag(AssetCreationOptions.StorageEncrypted))
            {
                contentKeyData = this.Asset.ContentKeys.Where(c => c.ContentKeyType == ContentKeyType.StorageEncryption).FirstOrDefault();
                if (contentKeyData == null)
                {
                    throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, StringTable.StorageEncryptionContentKeyIsMissing, this.Asset.Id));
                }

                fileEncryption = new FileEncryption(contentKeyData.GetClearKeyValue(), EncryptionUtils.GetKeyIdAsGuid(contentKeyData.Id));
            }

            EventHandler <BlobTransferProgressChangedEventArgs> handler = (s, e) => OnUploadProgressChanged(path, e);

            blobTransferClient.TransferProgressChanged += handler;

            MediaRetryPolicy retryPolicy = this.GetMediaContext().MediaServicesClassFactory.GetBlobStorageClientRetryPolicy();

            return(blobTransferClient.UploadBlob(
                       new Uri(locator.BaseUri),
                       path,
                       null,
                       fileEncryption,
                       token,
                       retryPolicy.AsAzureStorageClientRetryPolicy(),
                       () => locator.ContentAccessComponent)
                   .ContinueWith(
                       ts =>
            {
                blobTransferClient.TransferProgressChanged -= handler;
                this.PostUploadAction(ts, path, fileEncryption, assetCreationOptions, token);
            }));
        }
        private static void CreateFairPlayAssetDeliveryPolicy(IAsset asset, IContentKey key)
        {
            var kdPolicy = _context.ContentKeyAuthorizationPolicies.Where(p => p.Id == key.AuthorizationPolicyId).Single();
            var kdOption = kdPolicy.Options.Single(o => o.KeyDeliveryType == ContentKeyDeliveryType.FairPlay);

            FairPlayConfiguration configFP = JsonConvert.DeserializeObject <FairPlayConfiguration>(kdOption.KeyDeliveryConfiguration);

            // Get the FairPlay license service URL.
            Uri acquisitionUrl = key.GetKeyDeliveryUrl(ContentKeyDeliveryType.FairPlay);

            Dictionary <AssetDeliveryPolicyConfigurationKey, string> assetDeliveryPolicyConfiguration =
                new Dictionary <AssetDeliveryPolicyConfigurationKey, string>
            {
                { AssetDeliveryPolicyConfigurationKey.FairPlayLicenseAcquisitionUrl, acquisitionUrl.ToString() },
                { AssetDeliveryPolicyConfigurationKey.CommonEncryptionIVForCbcs, configFP.ContentEncryptionIV }
            };

            var assetDeliveryPolicy = _context.AssetDeliveryPolicies.Create(
                "FairPlay AssetDeliveryPolicy",
                AssetDeliveryPolicyType.DynamicCommonEncryptionCbcs,
                AssetDeliveryProtocol.HLS,
                assetDeliveryPolicyConfiguration);

            // Add AssetDelivery Policy to the asset
            asset.DeliveryPolicies.Add(assetDeliveryPolicy);
        }
예제 #19
0
        private IContentKey[] GetContentKeys(ContentProtection contentProtection)
        {
            List <IContentKey> contentKeys = new List <IContentKey>();

            if (contentProtection.AES)
            {
                ContentKeyType keyType    = ContentKeyType.EnvelopeEncryption;
                string         keyName    = Constants.Media.ContentProtection.ContentKeyNameAes;
                IContentKey    contentKey = GetContentKey(keyType, keyName, contentProtection);
                contentKeys.Add(contentKey);
            }
            if (contentProtection.DRMPlayReady && contentProtection.DRMWidevine)
            {
                ContentKeyType keyType    = ContentKeyType.CommonEncryption;
                string         keyName    = Constants.Media.ContentProtection.ContentKeyNameDrmPlayReadyWidevine;
                IContentKey    contentKey = GetContentKey(keyType, keyName, contentProtection);
                contentKeys.Add(contentKey);
            }
            else if (contentProtection.DRMPlayReady)
            {
                ContentKeyType keyType    = ContentKeyType.CommonEncryption;
                string         keyName    = Constants.Media.ContentProtection.ContentKeyNameDrmPlayReady;
                IContentKey    contentKey = GetContentKey(keyType, keyName, contentProtection);
                contentKeys.Add(contentKey);
            }
            else if (contentProtection.DRMWidevine)
            {
                ContentKeyType keyType    = ContentKeyType.CommonEncryption;
                string         keyName    = Constants.Media.ContentProtection.ContentKeyNameDrmWidevine;
                IContentKey    contentKey = GetContentKey(keyType, keyName, contentProtection);
                contentKeys.Add(contentKey);
            }
            return(contentKeys.ToArray());
        }
        public void ShouldDeleteAssetWithCommonEncryptionContentKey()
        {
            var dataContext2 = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext();

            // Note that this file is not really PlayReady encrypted.  For the purposes of this test that is okay.
            IAsset asset   = AssetTests.CreateAsset(_mediaContext, Path.GetFullPath(WindowsAzureMediaServicesTestConfiguration.SmallWmv), AssetCreationOptions.CommonEncryptionProtected);
            string assetId = asset.Id;
            string fileId  = asset.AssetFiles.ToList()[0].Id;

            Guid keyId = Guid.NewGuid();

            byte[]      contentKeyBytes = GetRandomBuffer(16);
            IContentKey key             = _mediaContext.ContentKeys.Create(keyId, contentKeyBytes);

            asset.ContentKeys.Add(key);

            string keyIdentifier = key.Id;

            asset.Delete();

            IAsset resultAsset = dataContext2.Assets.Where(a => a.Id == assetId).FirstOrDefault();

            Assert.IsNull(resultAsset, "Asset was deleted we should not be able to query it by identifier.");

            IAssetFile resultFile = dataContext2.Files.Where(f => f.Id == fileId).FirstOrDefault();

            Assert.IsNull(resultFile, "Asset was deleted we should not be able to query its associated File by identifier.");

            // The content key should not exists
            IContentKey resultContentKey = dataContext2.ContentKeys.Where(c => c.Id == keyIdentifier).FirstOrDefault();

            Assert.IsNull(resultContentKey, "Common Encryption Content Key should be deleted by deleting the asset");
        }
        static public void AddOpenAuthorizationPolicy(IContentKey contentKey)
        {
            // Create ContentKeyAuthorizationPolicy with Open restrictions and create authorization policy
            IContentKeyAuthorizationPolicy policy = context.ContentKeyAuthorizationPolicies.CreateAsync("Open Authorization Policy").Result;

            List <ContentKeyAuthorizationPolicyRestriction> restrictions = new List <ContentKeyAuthorizationPolicyRestriction>();
            ContentKeyAuthorizationPolicyRestriction        restriction  =
                new ContentKeyAuthorizationPolicyRestriction
            {
                Name = "HLS Open Authorization Policy",
                KeyRestrictionType = (int)ContentKeyRestrictionType.Open,
                Requirements       = null // no requirements needed for HLS
            };

            restrictions.Add(restriction);

            IContentKeyAuthorizationPolicyOption policyOption =
                context.ContentKeyAuthorizationPolicyOptions.Create(
                    "policy",
                    ContentKeyDeliveryType.BaselineHttp,
                    restrictions,
                    "");

            policy.Options.Add(policyOption);

            // Add ContentKeyAutorizationPolicy to ContentKey
            contentKey.AuthorizationPolicyId = policy.Id;
            IContentKey updatedKey = contentKey.UpdateAsync().Result;
        }
예제 #22
0
        static public IContentKeyAuthorizationPolicy AddOpenAuthorizationPolicy(IContentKey contentKey, ContentKeyDeliveryType contentkeydeliverytype, string keydeliveryconfig, CloudMediaContext _context)
        {
            // Create ContentKeyAuthorizationPolicy with Open restrictions
            // and create authorization policy
            List <ContentKeyAuthorizationPolicyRestriction> restrictions = new List <ContentKeyAuthorizationPolicyRestriction>
            {
                new ContentKeyAuthorizationPolicyRestriction
                {
                    Name = "Open",
                    KeyRestrictionType = (int)ContentKeyRestrictionType.Open,
                    Requirements       = null
                }
            };

            IContentKeyAuthorizationPolicyOption policyOption =
                _context.ContentKeyAuthorizationPolicyOptions.Create(
                    "policy",
                    contentkeydeliverytype,
                    restrictions,
                    keydeliveryconfig);

            IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = _context.
                                                                           ContentKeyAuthorizationPolicies.
                                                                           CreateAsync("Open Authorization Policy").Result;

            contentKeyAuthorizationPolicy.Options.Add(policyOption);

            // Associate the content key authorization policy with the content key.
            contentKey.AuthorizationPolicyId = contentKeyAuthorizationPolicy.Id;
            contentKey = contentKey.UpdateAsync().Result;

            return(contentKeyAuthorizationPolicy);
        }
        public override void HandleExecute(Common.workflow.ChainRequest request)
        {
            myRequest = (ButlerProcessRequest)request;
            Setup();
            _MediaServiceContext = new CloudMediaContext(myRequest.MediaAccountName, myRequest.MediaAccountKey);
            IAsset encodedAsset = (from m in _MediaServiceContext.Assets select m).Where(m => m.Id == myRequest.AssetId).FirstOrDefault();

            //Create key
            IContentKey key = CreateEnvelopeTypeContentKey(encodedAsset);
            //Create Token Template
            string tokenTemplateString = AddTokenRestrictedAuthorizationPolicy(key);

            Trace.TraceInformation("Added authorization policy: {0}", key.AuthorizationPolicyId);
            //create Delivery Policy
            CreateAssetDeliveryPolicy(encodedAsset, key);

            if (!String.IsNullOrEmpty(tokenTemplateString))
            {
                // Deserializes a string containing an Xml representation of a TokenRestrictionTemplate
                // back into a TokenRestrictionTemplate class instance.
                TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString);

                // Generate a test token based on the data in the given TokenRestrictionTemplate.
                // Note, you need to pass the key id Guid because we specified
                // TokenClaim.ContentKeyIdentifierClaim in during the creation of TokenRestrictionTemplate.
                Guid   rawkey    = EncryptionUtils.GetKeyIdAsGuid(key.Id);
                string testToken = TokenRestrictionTemplateSerializer.GenerateTestToken(tokenTemplate, null, rawkey);
                Trace.TraceInformation("The authorization token is:\n{0}", testToken);
                myRequest.Log.Add("The authorization token");
                myRequest.Log.Add(testToken);
                myRequest.Log.Add("");
            }
        }
예제 #24
0
        /// <summary>
        /// This is a helper method to setup a Content Key for delivery from Azure Media Services
        /// </summary>
        /// <param name="context">The CloudMediaContext instance used to communicate with Azure Media Services</param>
        /// <param name="restrictions">One or more restrictions to add to the ContentKeyAuthorizationPolicy associated with the ContentKey</param>
        /// <returns>A ContentKey that is configured for delivery to clients</returns>
        private static IContentKey SetupContentKey(CloudMediaContext context, List <ContentKeyAuthorizationPolicyRestriction> restrictions)
        {
            //
            //  Create the ContentKeyAuthorizationPolicyOption
            //
            IContentKeyAuthorizationPolicyOption option =
                context.ContentKeyAuthorizationPolicyOptions.Create("Option with Token Restriction",
                                                                    ContentKeyDeliveryType.BaselineHttp,
                                                                    restrictions,
                                                                    null);

            //
            //  Create the ContentKeyAuthorizationPolicy and add the option from above
            //
            IContentKeyAuthorizationPolicy policy = context.ContentKeyAuthorizationPolicies.CreateAsync("Policy to illustrate integration with ACS").Result;

            policy.Options.Add(option);

            //
            //  Create the ContentKey and associate the policy from above
            //
            byte[]      keyValue   = GetRandomKeyValue();
            Guid        keyId      = Guid.NewGuid();
            IContentKey contentKey = context.ContentKeys.Create(keyId, keyValue, "Test Key", ContentKeyType.EnvelopeEncryption);

            contentKey.AuthorizationPolicyId = policy.Id;
            contentKey.Update();

            return(contentKey);
        }
        public static void AddOpenAuthorizationPolicy(IContentKey contentKey)
        {
            // Create ContentKeyAuthorizationPolicy with Open restrictions
            // and create authorization policy
            IContentKeyAuthorizationPolicy policy = _context.
                                    ContentKeyAuthorizationPolicies.
                                    CreateAsync("Open Authorization Policy").Result;

            List<ContentKeyAuthorizationPolicyRestriction> restrictions =
                new List<ContentKeyAuthorizationPolicyRestriction>();

            ContentKeyAuthorizationPolicyRestriction restriction =
                new ContentKeyAuthorizationPolicyRestriction
                {
                    Name = "HLS Open Authorization Policy",
                    KeyRestrictionType = (int)ContentKeyRestrictionType.Open,
                    Requirements = null // no requirements needed for HLS
                };

            restrictions.Add(restriction);

            IContentKeyAuthorizationPolicyOption policyOption =
                _context.ContentKeyAuthorizationPolicyOptions.Create(
                "policy",
                ContentKeyDeliveryType.BaselineHttp,
                restrictions,
                "");

            policy.Options.Add(policyOption);

            // Add ContentKeyAutorizationPolicy to ContentKey
            contentKey.AuthorizationPolicyId = policy.Id;
            IContentKey updatedKey = contentKey.UpdateAsync().Result;
            Console.WriteLine("Adding Key to Asset: Key ID is " + updatedKey.Id);
        }
예제 #26
0
        static public void AddOpenAuthorizationPolicy(IContentKey contentKey)
        {
            // Create ContentKeyAuthorizationPolicy with Open restrictions
            // and create authorization policy

            List <ContentKeyAuthorizationPolicyRestriction> restrictions = new List <ContentKeyAuthorizationPolicyRestriction>
            {
                new ContentKeyAuthorizationPolicyRestriction
                {
                    Name = "Open",
                    KeyRestrictionType = (int)ContentKeyRestrictionType.Open,
                    Requirements       = null
                }
            };

            // Configure PlayReady license template.
            string newLicenseTemplate = ConfigurePlayReadyLicenseTemplate();

            IContentKeyAuthorizationPolicyOption policyOption =
                _context.ContentKeyAuthorizationPolicyOptions.Create("",
                                                                     ContentKeyDeliveryType.PlayReadyLicense,
                                                                     restrictions, newLicenseTemplate);

            IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = _context.
                                                                           ContentKeyAuthorizationPolicies.
                                                                           CreateAsync("Deliver Common Content Key with no restrictions").
                                                                           Result;


            contentKeyAuthorizationPolicy.Options.Add(policyOption);

            // Associate the content key authorization policy with the content key.
            contentKey.AuthorizationPolicyId = contentKeyAuthorizationPolicy.Id;
            contentKey = contentKey.UpdateAsync().Result;
        }
예제 #27
0
        /// <summary>
        /// Removes locators, delivery policies and keys associated with an asset
        /// </summary>
        /// <param name="asset"></param>
        private static void CleanUpAsset(IAsset asset)
        {
            foreach (var locator in asset.Locators)
            {
                ILocator locatorRefreshed = _context.Locators.Where(p => p.Id == locator.Id).FirstOrDefault();
                if (locatorRefreshed != null)
                {
                    locatorRefreshed.Delete();
                }
            }

            var deliveryPolicies = asset.DeliveryPolicies.ToList();

            foreach (var deliveryPolicy in deliveryPolicies)
            {
                asset.DeliveryPolicies.Remove(deliveryPolicy);
                var deliveryPolicyRefreshed = _context.AssetDeliveryPolicies.Where(p => p.Id == deliveryPolicy.Id).FirstOrDefault();
                if (deliveryPolicyRefreshed != null)
                {
                    deliveryPolicyRefreshed.Delete();
                }
            }

            var keys = asset.ContentKeys.ToList();

            foreach (var key in keys)
            {
                asset.ContentKeys.Remove(key);
                IContentKey keyRefreshed = _context.ContentKeys.Where(p => p.Id == key.Id).FirstOrDefault();
                if (keyRefreshed != null)
                {
                    keyRefreshed.Delete();
                }
            }
        }
예제 #28
0
        public string[] GetProtectionTypes(IAsset asset)
        {
            List <string>        protectionTypes = new List <string>();
            IAssetDeliveryPolicy deliveryPolicy  = asset.DeliveryPolicies.Where(p => p.AssetDeliveryPolicyType == AssetDeliveryPolicyType.DynamicEnvelopeEncryption).SingleOrDefault();

            if (deliveryPolicy != null)
            {
                protectionTypes.Add(MediaProtection.AES.ToString());
            }
            deliveryPolicy = asset.DeliveryPolicies.Where(p => p.AssetDeliveryPolicyType == AssetDeliveryPolicyType.DynamicCommonEncryption).SingleOrDefault();
            if (deliveryPolicy != null)
            {
                IContentKey contentKey = asset.ContentKeys.Where(k => k.ContentKeyType == ContentKeyType.CommonEncryption).SingleOrDefault();
                if (contentKey != null)
                {
                    IContentKeyAuthorizationPolicy authPolicy = GetEntityById(MediaEntity.ContentKeyAuthPolicy, contentKey.AuthorizationPolicyId) as IContentKeyAuthorizationPolicy;
                    if (authPolicy != null)
                    {
                        IContentKeyAuthorizationPolicyOption policyOption = authPolicy.Options.Where(o => o.KeyDeliveryType == ContentKeyDeliveryType.PlayReadyLicense).SingleOrDefault();
                        if (policyOption != null)
                        {
                            protectionTypes.Add(MediaProtection.PlayReady.ToString());
                        }
                        policyOption = authPolicy.Options.Where(o => o.KeyDeliveryType == ContentKeyDeliveryType.Widevine).SingleOrDefault();
                        if (policyOption != null)
                        {
                            protectionTypes.Add(MediaProtection.Widevine.ToString());
                        }
                    }
                }
            }
            return(protectionTypes.ToArray());
        }
예제 #29
0
        static public void CreateAssetDeliveryPolicy(IAsset asset, IContentKey key)
        {
            Uri keyAcquisitionUri = key.GetKeyDeliveryUrl(ContentKeyDeliveryType.BaselineHttp);

            string 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.
            Dictionary <AssetDeliveryPolicyConfigurationKey, string> assetDeliveryPolicyConfiguration =
                new Dictionary <AssetDeliveryPolicyConfigurationKey, string>
            {
                { AssetDeliveryPolicyConfigurationKey.EnvelopeKeyAcquisitionUrl, keyAcquisitionUri.ToString() }
            };

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

            // Add AssetDelivery Policy to the asset
            asset.DeliveryPolicies.Add(assetDeliveryPolicy);
            Console.WriteLine();
            Console.WriteLine("Adding Asset Delivery Policy: " +
                              assetDeliveryPolicy.AssetDeliveryPolicyType);
        }
        private static string ConfigureFairPlayPolicyOptions()
        {
            // For testing you can provide all zeroes for ASK bytes together with the cert from Apple FPS SDK.
            // However, for production you must use a real ASK from Apple bound to a real prod certificate.
            byte[] askBytes = string.IsNullOrEmpty(_fairPlayASK) ? Guid.NewGuid().ToByteArray() : System.Text.Encoding.UTF8.GetBytes(_fairPlayASK);
            var    askId    = string.IsNullOrEmpty(_fairPlayASKId) ? Guid.NewGuid() : Guid.Parse(_fairPlayASKId);

            // Key delivery retrieves askKey by askId and uses this key to generate the response.
            IContentKey askKey = _context.ContentKeys.Create(askId, askBytes, "askKey", ContentKeyType.FairPlayASk);

            //Customer password for creating the .pfx file.
            string pfxPassword = _fairPlayPFXPassword;

            // Key delivery retrieves pfxPasswordKey by pfxPasswordId and uses this key to generate the response.
            var pfxPasswordId = Guid.NewGuid();

            byte[]      pfxPasswordBytes = System.Text.Encoding.UTF8.GetBytes(pfxPassword);
            IContentKey pfxPasswordKey   = _context.ContentKeys.Create(pfxPasswordId, pfxPasswordBytes, "pfxPasswordKey", ContentKeyType.FairPlayPfxPassword);

            // iv - 16 bytes random value, must match the iv in the asset delivery policy.
            byte[] iv = Guid.NewGuid().ToByteArray();

            //Specify the .pfx file created by the customer.
            var appCert = new X509Certificate2(_fairPlayPFXPath, pfxPassword, X509KeyStorageFlags.Exportable);

            string FairPlayConfiguration =
                Microsoft.WindowsAzure.MediaServices.Client.FairPlay.FairPlayConfiguration.CreateSerializedFairPlayOptionConfiguration(
                    appCert,
                    pfxPassword,
                    pfxPasswordId,
                    askId,
                    iv);

            return(FairPlayConfiguration);
        }
예제 #31
0
        static void Main(string[] args)
        {
            //
            //  Get all of the values we need from the App.Config
            //
            string mediaServicesAccountName = ConfigurationManager.AppSettings["MediaServiceAccountName"];
            string mediaServicesAccountKey  = ConfigurationManager.AppSettings["MediaServiceAccountKey"];
            string clientId         = ConfigurationManager.AppSettings["AcsAccountName"];
            string clientSecret     = ConfigurationManager.AppSettings["AcsAccountKey"];
            string issuerString     = ConfigurationManager.AppSettings["AcsEndpoint"];
            string scopeString      = ConfigurationManager.AppSettings["AcsScope"];
            string signingKeyString = ConfigurationManager.AppSettings["AcsSigningKey"];

            byte[] signingKey = Convert.FromBase64String(signingKeyString);

            //
            //  Create the context to talk to Azure Media Services
            //
            MediaServicesCredentials creds   = new MediaServicesCredentials(mediaServicesAccountName, mediaServicesAccountKey);
            CloudMediaContext        context = new CloudMediaContext(creds);

            //
            //  Setup Media Services for Key Delivery of an Envelope Content Key with a Token Restriction.
            //  The GetTokenRestriction method has all of the details on how the ACS parameters from the App.Config
            //  are used to configure the token validation logic associated with delivering the content key.
            //
            List <ContentKeyAuthorizationPolicyRestriction> restrictions = GetTokenRestriction("Token Restriction using token from ACS", issuerString, scopeString, signingKey);

            IContentKey contentKey = SetupContentKey(context, restrictions);

            //
            //  Now simulate a client downloading the content key to use for playback by
            //  using ACS to get an authentication token and using the token to download
            //  the Envelope key from the Key Delivery service.
            //
            string authToken = GetToken(clientId, clientSecret, scopeString, issuerString);

            Uri keyUrl = contentKey.GetKeyDeliveryUrl(ContentKeyDeliveryType.BaselineHttp);

            using (WebClient client = new WebClient())
            {
                Console.WriteLine("Token=Bearer " + authToken);
                client.Headers["Authorization"] = "Bearer " + authToken;
                byte[] downloadedKeyValue;
                try
                {
                    downloadedKeyValue      = client.DownloadData(keyUrl);
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("\nContent Key acquired successfully!");
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("\nKey acquisition failed.\n{0}", ex.Message);
                }
            }
            Console.ResetColor();
            Console.ReadLine();
        }
        public static IContentKeyAuthorizationPolicy CreateTestPolicy(CloudMediaContext mediaContext, string name, List<IContentKeyAuthorizationPolicyOption> policyOptions, ref IContentKey contentKey)
        {
            IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = mediaContext.ContentKeyAuthorizationPolicies.CreateAsync(name).Result;

            foreach (IContentKeyAuthorizationPolicyOption option in policyOptions)
            {
                contentKeyAuthorizationPolicy.Options.Add(option);
            }

            // Associate the content key authorization policy with the content key
            contentKey.AuthorizationPolicyId = contentKeyAuthorizationPolicy.Id;
            contentKey = contentKey.UpdateAsync().Result;

            return contentKeyAuthorizationPolicy;
        }
        public static void AddOpenAuthorizationPolicy(IContentKey contentKey)
        {
            // Create ContentKeyAuthorizationPolicy with Open restrictions
            // and create authorization policy

            List<ContentKeyAuthorizationPolicyRestriction> restrictions = new List<ContentKeyAuthorizationPolicyRestriction>
            {
                new ContentKeyAuthorizationPolicyRestriction
                {
                    Name = "Open",
                    KeyRestrictionType = (int)ContentKeyRestrictionType.Open,
                    Requirements = null
                }
            };

            // Configure PlayReady and Widevine license templates.
            string PlayReadyLicenseTemplate = ConfigurePlayReadyLicenseTemplate();

            string WidevineLicenseTemplate = ConfigureWidevineLicenseTemplate();

            IContentKeyAuthorizationPolicyOption PlayReadyPolicy =
                _context.ContentKeyAuthorizationPolicyOptions.Create("",
                    ContentKeyDeliveryType.PlayReadyLicense,
                        restrictions, PlayReadyLicenseTemplate);

            IContentKeyAuthorizationPolicyOption WidevinePolicy =
                _context.ContentKeyAuthorizationPolicyOptions.Create("",
                    ContentKeyDeliveryType.Widevine,
                    restrictions, WidevineLicenseTemplate);

            IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = _context.
                        ContentKeyAuthorizationPolicies.
                        CreateAsync("Deliver Common Content Key with no restrictions").
                        Result;

            contentKeyAuthorizationPolicy.Options.Add(PlayReadyPolicy);
            contentKeyAuthorizationPolicy.Options.Add(WidevinePolicy);
            // Associate the content key authorization policy with the content key.
            contentKey.AuthorizationPolicyId = contentKeyAuthorizationPolicy.Id;
            contentKey = contentKey.UpdateAsync().Result;
        }
        private string AddTokenRestrictedAuthorizationPolicy(IContentKey contentKey)
        {
            string tokenTemplateString = GenerateTokenRequirements();

            IContentKeyAuthorizationPolicy policy = _MediaServiceContext.
                                    ContentKeyAuthorizationPolicies.
                                    CreateAsync(myConfig.policyName).Result;

            List<ContentKeyAuthorizationPolicyRestriction> restrictions =
                    new List<ContentKeyAuthorizationPolicyRestriction>();

            ContentKeyAuthorizationPolicyRestriction restriction =
                    new ContentKeyAuthorizationPolicyRestriction
                    {
                        Name = "Token Authorization Policy",
                        KeyRestrictionType = (int)ContentKeyRestrictionType.TokenRestricted,
                        Requirements = tokenTemplateString
                    };

            restrictions.Add(restriction);

            //You could have multiple options
            IContentKeyAuthorizationPolicyOption policyOption =
                _MediaServiceContext.ContentKeyAuthorizationPolicyOptions.Create(
                    "Token option for HLS",
                    ContentKeyDeliveryType.BaselineHttp,
                    restrictions,
                    null  // no key delivery data is needed for HLS
                    );

            policy.Options.Add(policyOption);

            // Add ContentKeyAutorizationPolicy to ContentKey
            contentKey.AuthorizationPolicyId = policy.Id;
            IContentKey updatedKey = contentKey.UpdateAsync().Result;
            Trace.TraceInformation("Adding Key to Asset: Key ID is " + updatedKey.Id);

            return tokenTemplateString;
        }
        public static IContentKeyAuthorizationPolicyOption AddOpenAuthorizationPolicyOption(IContentKey contentKey, ContentKeyDeliveryType contentkeydeliverytype, string keydeliveryconfig, CloudMediaContext _context)
        {
            // Create ContentKeyAuthorizationPolicy with Open restrictions
            // and create authorization policy
            List<ContentKeyAuthorizationPolicyRestriction> restrictions = new List<ContentKeyAuthorizationPolicyRestriction>
            {
            new ContentKeyAuthorizationPolicyRestriction
            {
            Name = "Open Authorization Policy",
            KeyRestrictionType = (int)ContentKeyRestrictionType.Open,
            Requirements = null
            }
            };

            IContentKeyAuthorizationPolicyOption policyOption =
                _context.ContentKeyAuthorizationPolicyOptions.Create(
                "Open option",
                contentkeydeliverytype,
                restrictions,
                keydeliveryconfig);

            return policyOption;
        }
예제 #36
0
        static public IAssetDeliveryPolicy CreateAssetDeliveryPolicyAES(IAsset asset, IContentKey key, AssetDeliveryProtocol assetdeliveryprotocol, string name, CloudMediaContext _context, Uri keyAcquisitionUri)
        {
            // if user does not specify a custom LA URL, let's use the AES key server from Azure Media Services
            if (keyAcquisitionUri == null)
            {
                keyAcquisitionUri = key.GetKeyDeliveryUrl(ContentKeyDeliveryType.BaselineHttp);
            }

            // let's key the url with the key id parameter
            UriBuilder uriBuilder = new UriBuilder(keyAcquisitionUri);
            uriBuilder.Query = String.Empty;
            keyAcquisitionUri = uriBuilder.Uri;

            // Removed in March 2016. In order to use EnvelopeBaseKeyAcquisitionUrl and reuse the same policy for several assets
            //string 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.
            Dictionary<AssetDeliveryPolicyConfigurationKey, string> assetDeliveryPolicyConfiguration =
                new Dictionary<AssetDeliveryPolicyConfigurationKey, string>
            {
                {AssetDeliveryPolicyConfigurationKey.EnvelopeBaseKeyAcquisitionUrl, keyAcquisitionUri.ToString()}
                //{AssetDeliveryPolicyConfigurationKey.EnvelopeKeyAcquisitionUrl, keyAcquisitionUri.ToString()},
                //{AssetDeliveryPolicyConfigurationKey.EnvelopeEncryptionIVAsBase64, envelopeEncryptionIV}
            };

            IAssetDeliveryPolicy assetDeliveryPolicy =
                _context.AssetDeliveryPolicies.Create(
                            name,
                            AssetDeliveryPolicyType.DynamicEnvelopeEncryption,
                            assetdeliveryprotocol,
                            assetDeliveryPolicyConfiguration);

            // Add AssetDelivery Policy to the asset
            asset.DeliveryPolicies.Add(assetDeliveryPolicy);
            return assetDeliveryPolicy;
        }
예제 #37
0
        static public IAssetDeliveryPolicy CreateAssetDeliveryPolicyCENC(IAsset asset, IContentKey key, AddDynamicEncryptionFrame1 form1, string name, CloudMediaContext _context, Uri playreadyAcquisitionUrl = null, bool playreadyEncodeLAURLForSilverlight = false, string widevineAcquisitionUrl = null)
        {
            Dictionary<AssetDeliveryPolicyConfigurationKey, string> assetDeliveryPolicyConfiguration = new Dictionary<AssetDeliveryPolicyConfigurationKey, string>();

            // PlayReady
            if (form1.PlayReadyPackaging)
            {
                string stringPRacquisitionUrl;
                if (playreadyEncodeLAURLForSilverlight && playreadyAcquisitionUrl != null)
                {
                    stringPRacquisitionUrl = playreadyAcquisitionUrl.ToString().Replace("&", "%26");
                }
                else
                {
                    if (playreadyAcquisitionUrl == null)
                    {
                        playreadyAcquisitionUrl = key.GetKeyDeliveryUrl(ContentKeyDeliveryType.PlayReadyLicense);
                    }
                    stringPRacquisitionUrl = System.Security.SecurityElement.Escape(playreadyAcquisitionUrl.ToString());
                }

                assetDeliveryPolicyConfiguration.Add(AssetDeliveryPolicyConfigurationKey.PlayReadyLicenseAcquisitionUrl, stringPRacquisitionUrl);

                if (form1.PlayReadyCustomAttributes != null) // let's add custom attributes
                {
                    assetDeliveryPolicyConfiguration.Add(AssetDeliveryPolicyConfigurationKey.PlayReadyCustomAttributes, form1.PlayReadyCustomAttributes);
                }
            }


            // Widevine
            if (form1.WidevinePackaging) // let's add Widevine
            {
                if (widevineAcquisitionUrl == null)
                {
                    widevineAcquisitionUrl = key.GetKeyDeliveryUrl(ContentKeyDeliveryType.Widevine).ToString();
                }
                // let's get the url without the key id parameter
                UriBuilder uriBuilder = new UriBuilder(widevineAcquisitionUrl);
                uriBuilder.Query = String.Empty;
                widevineAcquisitionUrl = uriBuilder.Uri.ToString();

                assetDeliveryPolicyConfiguration.Add(AssetDeliveryPolicyConfigurationKey.WidevineBaseLicenseAcquisitionUrl, widevineAcquisitionUrl);
            }

            // let's check the protocol: DASH only if only Widevine packaging
            var protocol = form1.GetAssetDeliveryProtocol;
            if (!form1.PlayReadyPackaging && form1.WidevinePackaging)
            {
                protocol = AssetDeliveryProtocol.Dash;
            }


            var assetDeliveryPolicy = _context.AssetDeliveryPolicies.Create(
                                                                            name,
                                                                            AssetDeliveryPolicyType.DynamicCommonEncryption,
                                                                            protocol,
                                                                            assetDeliveryPolicyConfiguration
                                                                            );

            // Add AssetDelivery Policy to the asset
            asset.DeliveryPolicies.Add(assetDeliveryPolicy);

            return assetDeliveryPolicy;
        }
        private void listViewAutOptions_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listViewAutOptions.SelectedIndices.Count > 0)
            {
                var it = listViewAutOptions.SelectedItems[0];
                string stringoptionid = it.SubItems[2].Text;
                SelectedOption = mycontext.ContentKeyAuthorizationPolicyOptions.Where(p => p.Id == stringoptionid).FirstOrDefault();

                KeyFromSelectedOption = ContentKeyDisplayed[listViewAutOptions.SelectedItems[0].Index];

                string tokenTemplateString = SelectedOption.Restrictions.FirstOrDefault().Requirements;
                if (!string.IsNullOrEmpty(tokenTemplateString))
                {
                    TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString);
                    textBoxAudience.Text = tokenTemplate.Audience.ToString();
                    textBoxIssuer.Text = tokenTemplate.Issuer.ToString();
                    checkBoxAddContentKeyIdentifierClaim.Checked = false;
                    groupBoxStartDate.Enabled = (tokenTemplate.TokenType == TokenType.JWT);
                    panelJWTX509Cert.Enabled = !(tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey));
                    TokenClaimsList.Clear();
                    foreach (var claim in tokenTemplate.RequiredClaims)
                    {
                        if (claim.ClaimType == TokenClaim.ContentKeyIdentifierClaimType)
                        {
                            checkBoxAddContentKeyIdentifierClaim.Checked = true;
                        }
                        else
                        {
                            TokenClaimsList.Add(new MyTokenClaim()
                            {
                                Type = claim.ClaimType,
                                Value = claim.ClaimValue
                            });
                        }
                    }
                }
                UpdateButtonOk();
            }
        }
        public static IContentKeyAuthorizationPolicyOption AddTokenRestrictedAuthorizationPolicyAES(IContentKey contentKey, string Audience, string Issuer, IList<TokenClaim> tokenclaimslist, bool AddContentKeyIdentifierClaim, TokenType tokentype, ExplorerTokenType detailedtokentype, TokenVerificationKey mytokenverificationkey, CloudMediaContext _context, string openIdDiscoveryPath = null)
        {
            string tokenTemplateString = GenerateTokenRequirements(tokentype, Audience, Issuer, tokenclaimslist, AddContentKeyIdentifierClaim, mytokenverificationkey, openIdDiscoveryPath);

            string tname = detailedtokentype.ToString();

            List<ContentKeyAuthorizationPolicyRestriction> restrictions =
                    new List<ContentKeyAuthorizationPolicyRestriction>();

            ContentKeyAuthorizationPolicyRestriction restriction =
                    new ContentKeyAuthorizationPolicyRestriction
                    {
                        Name = tname + " Token Authorization Policy",
                        KeyRestrictionType = (int)ContentKeyRestrictionType.TokenRestricted,
                        Requirements = tokenTemplateString
                    };

            restrictions.Add(restriction);

            //You could have multiple options 
            IContentKeyAuthorizationPolicyOption policyOption =
                _context.ContentKeyAuthorizationPolicyOptions.Create(
                    "Token option",
                    ContentKeyDeliveryType.BaselineHttp,
                    restrictions,
                    null  // no key delivery data is needed for HLS
                    );

            return policyOption;

        }
        public static IContentKeyAuthorizationPolicyOption AddTokenRestrictedAuthorizationPolicyPlayReady(IContentKey contentKey, string Audience, string Issuer, IList<TokenClaim> tokenclaimslist, bool AddContentKeyIdentifierClaim, TokenType tokentype, ExplorerTokenType detailedtokentype, TokenVerificationKey mytokenverificationkey, CloudMediaContext _context, string newLicenseTemplate, string openIdDiscoveryPath = null)
        {
            string tokenTemplateString = GenerateTokenRequirements(tokentype, Audience, Issuer, tokenclaimslist, AddContentKeyIdentifierClaim, mytokenverificationkey, openIdDiscoveryPath);
            string tname = detailedtokentype.ToString();

            List<ContentKeyAuthorizationPolicyRestriction> restrictions = new List<ContentKeyAuthorizationPolicyRestriction>
    {
        new ContentKeyAuthorizationPolicyRestriction
        {
            Name = tname+ " Token Authorization Policy",
            KeyRestrictionType = (int)ContentKeyRestrictionType.TokenRestricted,
            Requirements = tokenTemplateString,
        }
    };

            IContentKeyAuthorizationPolicyOption policyOption =
         _context.ContentKeyAuthorizationPolicyOptions.Create(tname + "Token option",
             ContentKeyDeliveryType.PlayReadyLicense,
                 restrictions, newLicenseTemplate);

            IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = _context.
                        ContentKeyAuthorizationPolicies.
                        CreateAsync("Deliver Common Content Key with no restrictions").
                        Result;


            return policyOption;
        }
예제 #41
0
        public IContentKey AddAuthorizationPolicyToContentKey(string assetID, CloudMediaContext mediaContext, IContentKey objIContentKey, string claimType, string claimValue, JwtSecurityToken token)
        {
           //we name auth policy same as asset
            var policy = mediaContext.ContentKeyAuthorizationPolicies.Where(c => c.Name == assetID).FirstOrDefault();

            // Create ContentKeyAuthorizationPolicy with restrictions and create authorization policy             
            if (policy == null)
            {
                policy = mediaContext.ContentKeyAuthorizationPolicies.CreateAsync(assetID).Result;
            }
           
            //naming policyOption same as asset
            var policyOption = mediaContext.ContentKeyAuthorizationPolicyOptions.Where(name => name.Name == assetID).FirstOrDefault();

            if (policyOption == null)
            {

                List<ContentKeyAuthorizationPolicyRestriction> restrictions = new List<ContentKeyAuthorizationPolicyRestriction>();

               

                TokenRestrictionTemplate template = new TokenRestrictionTemplate();
                template.TokenType = TokenType.JWT;
                //Using Active Directory Open ID discovery spec to use Json Web Keys during token verification
                template.OpenIdConnectDiscoveryDocument = new OpenIdConnectDiscoveryDocument("https://login.windows.net/common/.well-known/openid-configuration");
              


                //Ignore Empty claims
                if (!String.IsNullOrEmpty(claimType) && !String.IsNullOrEmpty(claimValue))
                {
                    template.RequiredClaims.Add(new TokenClaim(claimType, claimValue));
                }

                var audience = token.Audiences.First();
                template.Audience = audience;
                template.Issuer = token.Issuer;
                string requirements = TokenRestrictionTemplateSerializer.Serialize(template);

                ContentKeyAuthorizationPolicyRestriction restriction = new ContentKeyAuthorizationPolicyRestriction
                {
                    Name = "Authorization Policy with Token Restriction",
                    KeyRestrictionType = (int)ContentKeyRestrictionType.TokenRestricted,
                    Requirements = requirements
                };

                restrictions.Add(restriction);

                policyOption =
                    mediaContext.ContentKeyAuthorizationPolicyOptions.Create(assetID,
                        ContentKeyDeliveryType.BaselineHttp, restrictions, null);
                policy.Options.Add(policyOption);
                policy.UpdateAsync();
            }


            // Add ContentKeyAutorizationPolicy to ContentKey
            objIContentKey.AuthorizationPolicyId = policy.Id;
            IContentKey IContentKeyUpdated = objIContentKey.UpdateAsync().Result;

            return IContentKeyUpdated;
        }
        public static IContentKeyAuthorizationPolicyOption AddTokenRestrictedAuthorizationPolicyAES(IContentKey contentKey, string Audience, string Issuer, IList<TokenClaim> tokenclaimslist, bool AddContentKeyIdentifierClaim, TokenType tokentype, bool IsJWTKeySymmetric, TokenVerificationKey mytokenverificationkey, CloudMediaContext _context)
        {
            string tokenTemplateString = GenerateTokenRequirements(tokentype, Audience, Issuer, tokenclaimslist, AddContentKeyIdentifierClaim, mytokenverificationkey);

            string tname = ((IsJWTKeySymmetric) ? "Sym " : "Asym ") + ((tokentype == TokenType.SWT) ? "SWT " : "JWT ");

            List<ContentKeyAuthorizationPolicyRestriction> restrictions =
                    new List<ContentKeyAuthorizationPolicyRestriction>();

            ContentKeyAuthorizationPolicyRestriction restriction =
                    new ContentKeyAuthorizationPolicyRestriction
                    {
                        Name = "Token Authorization Policy",
                        KeyRestrictionType = (int)ContentKeyRestrictionType.TokenRestricted,
                        Requirements = tokenTemplateString
                    };

            restrictions.Add(restriction);

            //You could have multiple options
            IContentKeyAuthorizationPolicyOption policyOption =
                _context.ContentKeyAuthorizationPolicyOptions.Create(
                    "Token option",
                    ContentKeyDeliveryType.BaselineHttp,
                    restrictions,
                    null  // no key delivery data is needed for HLS
                    );

            return policyOption;
        }
        private void CleanupKeyAndPolicy(IContentKey contentKey, IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy, IContentKeyAuthorizationPolicyOption policyOption)
        {
            if (contentKey != null)
            {
                contentKey.Delete();
            }

            if (contentKeyAuthorizationPolicy != null)
            {
                contentKeyAuthorizationPolicy.Delete();
            }

            /*
            if (policyOption != null)
            {
                policyOption.Delete();
            }
            */
        }
        public static string AddTokenRestrictedAuthorizationPolicy(IContentKey contentKey)
        {
            string tokenTemplateString = GenerateTokenRequirements();

            IContentKeyAuthorizationPolicy policy = _context.
                                    ContentKeyAuthorizationPolicies.
                                    CreateAsync("HLS token restricted authorization policy").Result;

            List<ContentKeyAuthorizationPolicyRestriction> restrictions = new List<ContentKeyAuthorizationPolicyRestriction>
            {
                new ContentKeyAuthorizationPolicyRestriction 
                { 
                    Name = "Token Authorization Policy", 
                    KeyRestrictionType = (int)ContentKeyRestrictionType.TokenRestricted,
                    Requirements = tokenTemplateString, 
                }
            };

            // Configure PlayReady license template.
            string newLicenseTemplate = ConfigurePlayReadyLicenseTemplate();

            IContentKeyAuthorizationPolicyOption policyOption =
                _context.ContentKeyAuthorizationPolicyOptions.Create("Token option",
                    ContentKeyDeliveryType.PlayReadyLicense,
                        restrictions, newLicenseTemplate);

            IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = _context.
                        ContentKeyAuthorizationPolicies.
                        CreateAsync("Deliver Common Content Key with no restrictions").
                        Result;
            
            policy.Options.Add(policyOption);

            // Add ContentKeyAutorizationPolicy to ContentKey
            contentKeyAuthorizationPolicy.Options.Add(policyOption);

            // Associate the content key authorization policy with the content key
            contentKey.AuthorizationPolicyId = contentKeyAuthorizationPolicy.Id;
            contentKey = contentKey.UpdateAsync().Result;

            return tokenTemplateString;
        }
        static public void CreateAssetDeliveryPolicy(IAsset asset, IContentKey key)
        {
            Uri acquisitionUrl = key.GetKeyDeliveryUrl(ContentKeyDeliveryType.PlayReadyLicense);

            Dictionary<AssetDeliveryPolicyConfigurationKey, string> assetDeliveryPolicyConfiguration =
                new Dictionary<AssetDeliveryPolicyConfigurationKey, string>
            {
                {AssetDeliveryPolicyConfigurationKey.PlayReadyLicenseAcquisitionUrl, acquisitionUrl.ToString()},
            };

            var assetDeliveryPolicy = _context.AssetDeliveryPolicies.Create(
                    "AssetDeliveryPolicy",
                AssetDeliveryPolicyType.DynamicCommonEncryption,
                AssetDeliveryProtocol.SmoothStreaming,
                assetDeliveryPolicyConfiguration);

            // Add AssetDelivery Policy to the asset
            asset.DeliveryPolicies.Add(assetDeliveryPolicy);

            Console.WriteLine();
            Console.WriteLine("Adding Asset Delivery Policy: " +
                assetDeliveryPolicy.AssetDeliveryPolicyType);
        }
예제 #46
0
        private static void CreateAssetDeliveryPolicy(MediaContextBase context, IAsset asset, IContentKey key)
        {
            Uri keyAcquisitionUri = key.GetKeyDeliveryUrl(ContentKeyDeliveryType.BaselineHttp);

            string 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.
            Dictionary<AssetDeliveryPolicyConfigurationKey, string> assetDeliveryPolicyConfiguration = new Dictionary<AssetDeliveryPolicyConfigurationKey, string>
            {
                { AssetDeliveryPolicyConfigurationKey.EnvelopeKeyAcquisitionUrl, keyAcquisitionUri.ToString() },
                { AssetDeliveryPolicyConfigurationKey.EnvelopeEncryptionIVAsBase64, envelopeEncryptionIV }
            };

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

            // Add AssetDelivery Policy to the asset
            asset.DeliveryPolicies.Add(assetDeliveryPolicy);
        }
예제 #47
0
        private static void AddOpenRestrictedAuthorizationPolicy(MediaContextBase context, IContentKey contentKey)
        {
            // Create ContentKeyAuthorizationPolicy with Open restrictions and create authorization policy
            IContentKeyAuthorizationPolicy policy = context.ContentKeyAuthorizationPolicies.CreateAsync("Open Authorization Policy").Result;
            List<ContentKeyAuthorizationPolicyRestriction> restrictions = new List<ContentKeyAuthorizationPolicyRestriction>
                {
                    new ContentKeyAuthorizationPolicyRestriction
                    {
                        Name = "Open Authorization Policy",
                        KeyRestrictionType = (int)ContentKeyRestrictionType.Open,
                        Requirements = null // no requirements needed
                    }
                };
            IContentKeyAuthorizationPolicyOption policyOption = context.ContentKeyAuthorizationPolicyOptions.Create("Option", ContentKeyDeliveryType.BaselineHttp, restrictions, string.Empty);

            policy.Options.Add(policyOption);

            // Add ContentKeyAutorizationPolicy to ContentKey
            contentKey.AuthorizationPolicyId = policy.Id;
            IContentKey updatedKey = contentKey.UpdateAsync().Result;
        }
        public static void CreateAssetDeliveryPolicy(IAsset asset, IContentKey key)
        {
            // Get the PlayReady license service URL.
            Uri acquisitionUrl = key.GetKeyDeliveryUrl(ContentKeyDeliveryType.PlayReadyLicense);

            // GetKeyDeliveryUrl for Widevine attaches the KID to the URL.
            // For example: https://amsaccount1.keydelivery.mediaservices.windows.net/Widevine/?KID=268a6dcb-18c8-4648-8c95-f46429e4927c.
            // The WidevineBaseLicenseAcquisitionUrl (used below) also tells Dynamaic Encryption
            // to append /? KID =< keyId > to the end of the url when creating the manifest.
            // As a result Widevine license aquisition URL will have KID appended twice,
            // so we need to remove the KID that in the URL when we call GetKeyDeliveryUrl.

            Uri widevineUrl = key.GetKeyDeliveryUrl(ContentKeyDeliveryType.Widevine);
            UriBuilder uriBuilder = new UriBuilder(widevineUrl);
            uriBuilder.Query = String.Empty;
            widevineUrl = uriBuilder.Uri;

            Dictionary<AssetDeliveryPolicyConfigurationKey, string> assetDeliveryPolicyConfiguration =
                new Dictionary<AssetDeliveryPolicyConfigurationKey, string>
                {
                    {AssetDeliveryPolicyConfigurationKey.PlayReadyLicenseAcquisitionUrl, acquisitionUrl.ToString()},
                    {AssetDeliveryPolicyConfigurationKey.WidevineBaseLicenseAcquisitionUrl, widevineUrl.ToString()}

                };

            var assetDeliveryPolicy = _context.AssetDeliveryPolicies.Create(
                    "AssetDeliveryPolicy",
                AssetDeliveryPolicyType.DynamicCommonEncryption,
                AssetDeliveryProtocol.Dash,
                assetDeliveryPolicyConfiguration);

            // Add AssetDelivery Policy to the asset
            asset.DeliveryPolicies.Add(assetDeliveryPolicy);
        }
        static public IAssetDeliveryPolicy CreateAssetDeliveryPolicyCENC(IAsset asset, IContentKey key, AssetDeliveryProtocol assetdeliveryprotocol, string name, CloudMediaContext _context, Uri playreadyAcquisitionUrl = null, bool playreadyEncodeLAURLForSilverlight = false, string playreadyCustomAttributes = null, string widevineAcquisitionUrl = null)
        {
            string stringacquisitionUrl;
            if (playreadyEncodeLAURLForSilverlight && playreadyAcquisitionUrl != null)
            {
                stringacquisitionUrl = playreadyAcquisitionUrl.ToString().Replace("&", "%26");
            }
            else
            {
                if (playreadyAcquisitionUrl == null) playreadyAcquisitionUrl = key.GetKeyDeliveryUrl(ContentKeyDeliveryType.PlayReadyLicense);

                stringacquisitionUrl = System.Security.SecurityElement.Escape(playreadyAcquisitionUrl.ToString());
            }
            Dictionary<AssetDeliveryPolicyConfigurationKey, string> assetDeliveryPolicyConfiguration = new Dictionary<AssetDeliveryPolicyConfigurationKey, string>
            {
                {
                    AssetDeliveryPolicyConfigurationKey.PlayReadyLicenseAcquisitionUrl, stringacquisitionUrl
                },
         };
            if (playreadyCustomAttributes != null) // let's add custom attributes
            {
                assetDeliveryPolicyConfiguration.Add(AssetDeliveryPolicyConfigurationKey.PlayReadyCustomAttributes, playreadyCustomAttributes);
            }

            // Widevine
            if (widevineAcquisitionUrl != null) // let's add Widevine
            {
                assetDeliveryPolicyConfiguration.Add(AssetDeliveryPolicyConfigurationKey.WidevineLicenseAcquisitionUrl, widevineAcquisitionUrl);
            }

            var assetDeliveryPolicy = _context.AssetDeliveryPolicies.Create(
                name,
                AssetDeliveryPolicyType.DynamicCommonEncryption,
                assetdeliveryprotocol,
                assetDeliveryPolicyConfiguration);

            // Add AssetDelivery Policy to the asset
            asset.DeliveryPolicies.Add(assetDeliveryPolicy);

            return assetDeliveryPolicy;
        }
        public static IContentKey AddAuthorizationPolicyToContentKey(string assetID, CloudMediaContext mediaContext, IContentKey objIContentKey, string claimType, string claimValue)
        {
           //we name auth policy same as asset
            var policy = mediaContext.ContentKeyAuthorizationPolicies.Where(c => c.Name == assetID).FirstOrDefault();

            // Create ContentKeyAuthorizationPolicy with restrictions and create authorization policy             
            if (policy == null)
            {
                policy = mediaContext.ContentKeyAuthorizationPolicies.CreateAsync(assetID).Result;
            }
           
            //naming policyOption same as asset
            var policyOption = mediaContext.ContentKeyAuthorizationPolicyOptions.Where(name => name.Name == assetID).FirstOrDefault();

            if (policyOption == null)
            {

                List<ContentKeyAuthorizationPolicyRestriction> restrictions = new List<ContentKeyAuthorizationPolicyRestriction>();

                List<X509Certificate2> certs = GetX509Certificate2FromADMetadataEndpoint();
                JwtSecurityToken token = GetJwtSecurityToken();

                TokenRestrictionTemplate template = new TokenRestrictionTemplate();
                template.TokenType = TokenType.JWT;
                template.PrimaryVerificationKey = new X509CertTokenVerificationKey(certs[0]);
                certs.GetRange(1, certs.Count - 1).ForEach(c => template.AlternateVerificationKeys.Add(new X509CertTokenVerificationKey(c)));
               
                
                //Ignore Empty claims
                if (!String.IsNullOrEmpty(claimType) && !String.IsNullOrEmpty(claimValue))
                {
                    template.RequiredClaims.Add(new TokenClaim(claimType, claimValue));
                }

                var audience = token.Audiences.First();
                template.Audience = new Uri(audience);
                template.Issuer = new Uri(token.Issuer);
                string requirements = TokenRestrictionTemplateSerializer.Serialize(template);

                ContentKeyAuthorizationPolicyRestriction restriction = new ContentKeyAuthorizationPolicyRestriction
                {
                    Name = "Authorization Policy with Token Restriction",
                    KeyRestrictionType = (int)ContentKeyRestrictionType.TokenRestricted,
                    Requirements = requirements
                };

                restrictions.Add(restriction);

                policyOption =
                    mediaContext.ContentKeyAuthorizationPolicyOptions.Create(assetID,
                        ContentKeyDeliveryType.BaselineHttp, restrictions, null);
                policy.Options.Add(policyOption);
                policy.UpdateAsync();
            }


            // Add ContentKeyAutorizationPolicy to ContentKey
            objIContentKey.AuthorizationPolicyId = policy.Id;
            IContentKey IContentKeyUpdated = objIContentKey.UpdateAsync().Result;

            return IContentKeyUpdated;
        }
        static public IAssetDeliveryPolicy CreateAssetDeliveryPolicyAES(IAsset asset, IContentKey key, AssetDeliveryProtocol assetdeliveryprotocol, string name, CloudMediaContext _context, Uri keyAcquisitionUri)
        {
            // if user does not specify a custom LA URL, let's use the AES key server from Azure Media Services
            if (keyAcquisitionUri == null)
                keyAcquisitionUri = key.GetKeyDeliveryUrl(ContentKeyDeliveryType.BaselineHttp);

            string 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.
            Dictionary<AssetDeliveryPolicyConfigurationKey, string> assetDeliveryPolicyConfiguration =
                new Dictionary<AssetDeliveryPolicyConfigurationKey, string>
            {
                {AssetDeliveryPolicyConfigurationKey.EnvelopeKeyAcquisitionUrl, keyAcquisitionUri.ToString()},
                {AssetDeliveryPolicyConfigurationKey.EnvelopeEncryptionIVAsBase64, envelopeEncryptionIV}
            };

            IAssetDeliveryPolicy assetDeliveryPolicy =
                _context.AssetDeliveryPolicies.Create(
                            name,
                            AssetDeliveryPolicyType.DynamicEnvelopeEncryption,
                            assetdeliveryprotocol,
                            assetDeliveryPolicyConfiguration);

            // Add AssetDelivery Policy to the asset
            asset.DeliveryPolicies.Add(assetDeliveryPolicy);
            return assetDeliveryPolicy;
        }
        public static IContentKeyAuthorizationPolicyOption AddTokenRestrictedAuthorizationPolicyPlayReady(IContentKey contentKey, string Audience, string Issuer, IList<TokenClaim> tokenclaimslist, bool AddContentKeyIdentifierClaim, TokenType tokentype, bool IsJWTKeySymmetric, TokenVerificationKey mytokenverificationkey, CloudMediaContext _context, string newLicenseTemplate)
        {
            string tokenTemplateString = GenerateTokenRequirements(tokentype, Audience, Issuer, tokenclaimslist, AddContentKeyIdentifierClaim, mytokenverificationkey);
            string tname = ((IsJWTKeySymmetric) ? "Sym " : "Asym ") + ((tokentype == TokenType.SWT) ? "SWT " : " JWT ");

            List<ContentKeyAuthorizationPolicyRestriction> restrictions = new List<ContentKeyAuthorizationPolicyRestriction>
            {
            new ContentKeyAuthorizationPolicyRestriction
            {
            Name = tname+ "Token Authorization Policy",
            KeyRestrictionType = (int)ContentKeyRestrictionType.TokenRestricted,
            Requirements = tokenTemplateString,
            }
            };

            IContentKeyAuthorizationPolicyOption policyOption =
             _context.ContentKeyAuthorizationPolicyOptions.Create(tname + "Token option",
             ContentKeyDeliveryType.PlayReadyLicense,
                 restrictions, newLicenseTemplate);

            IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = _context.
                        ContentKeyAuthorizationPolicies.
                        CreateAsync("Deliver Common Content Key with no restrictions").
                        Result;

            return policyOption;
        }
 private static void UpdateDeleteContentKey(IContentKey key)
 {
     key.AuthorizationPolicyId = Guid.NewGuid().ToString();
     key.Update();
     key.AuthorizationPolicyId = Guid.NewGuid().ToString();
     key.UpdateAsync();
     key.Delete();
 }