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;
        }
Example #2
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;
        }
        private static string AddPlayReadyAndWidevineTokenRestrictedAuthorizationPolicy(IContentKey contentKey)
        {
            string tokenTemplateString = DRMHelper.GenerateTokenRequirementsString(_tokenPrimaryVerificationKey, _tokenAlternativeVerificationKey, _tokenScope, _tokenIssuer, true);

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

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

            IContentKeyAuthorizationPolicyOption PlayReadyPolicy = _context.ContentKeyAuthorizationPolicyOptions.Create("PlayReady token option", ContentKeyDeliveryType.PlayReadyLicense, restrictions, PlayReadyLicenseTemplate);
            IContentKeyAuthorizationPolicyOption WidevinePolicy  = _context.ContentKeyAuthorizationPolicyOptions.Create("Widevine token option", ContentKeyDeliveryType.Widevine, restrictions, WidevineLicenseTemplate);
            IContentKeyAuthorizationPolicy       contentKeyAuthorizationPolicy = _context.ContentKeyAuthorizationPolicies.CreateAsync("Deliver Common Content Key with token 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;

            return(tokenTemplateString);
        }
        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);
        }
Example #5
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);
        }
Example #6
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);
        }
 private static void UpdateDeleteContentKey(IContentKey key)
 {
     key.AuthorizationPolicyId = Guid.NewGuid().ToString();
     key.Update();
     key.AuthorizationPolicyId = Guid.NewGuid().ToString();
     key.UpdateAsync();
     key.Delete();
 }
Example #8
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 void TestCreateFairPlayAuthorizationPolicy()
        {
            Guid keyId = Guid.NewGuid();

            byte[]      contentKey = Guid.NewGuid().ToByteArray();
            IContentKey key        = _mediaContext.ContentKeys.Create(keyId, contentKey, "testKey", ContentKeyType.CommonEncryptionCbcs);

            byte[]      askBytes = Guid.NewGuid().ToByteArray();
            var         askId    = Guid.NewGuid();
            IContentKey askKey   = _mediaContext.ContentKeys.Create(askId, askBytes, "askKey", ContentKeyType.FairPlayASk);

            string pfxPassword   = "******";
            var    pfxPasswordId = Guid.NewGuid();

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

            byte[] iv = Guid.NewGuid().ToByteArray();

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

            var appCert = new X509Certificate2("amscer.pfx", pfxPassword, X509KeyStorageFlags.Exportable);

            string configuration = FairPlayConfiguration.CreateSerializedFairPlayOptionConfiguration(
                appCert,
                pfxPassword,
                pfxPasswordId,
                askId,
                iv);

            var policyOption = _mediaContext.ContentKeyAuthorizationPolicyOptions.Create(
                "fairPlayTest",
                ContentKeyDeliveryType.FairPlay,
                restrictions,
                configuration);

            var contentKeyAuthorizationPolicy = _mediaContext.ContentKeyAuthorizationPolicies.CreateAsync("Key no restrictions").Result;

            contentKeyAuthorizationPolicy.Options.Add(policyOption);

            key.AuthorizationPolicyId = contentKeyAuthorizationPolicy.Id;
            key = key.UpdateAsync().Result;

            key.Delete();
            pfxPasswordKey.Delete();
            askKey.Delete();
            contentKeyAuthorizationPolicy.Delete();
        }
        public void UpdateContentKeyAuthorizationPolicyId()
        {
            IContentKeyAuthorizationPolicy policy = _mediaContext.ContentKeyAuthorizationPolicies.CreateAsync(testRun).Result;
            IContentKey contentKey = _mediaContext.ContentKeys.CreateAsync(Guid.NewGuid(), new byte[16]).Result;

            contentKey.AuthorizationPolicyId = policy.Id;
            IContentKey updated = contentKey.UpdateAsync().Result;

            IContentKey updatedContentKey = _mediaContext.ContentKeys.Where(c => c.Id == contentKey.Id).FirstOrDefault();

            //var updatedWithPolicy = _dataContext.ContentKeys.Where(c => c.AuthorizationPolicyId == policy.Id).FirstOrDefault();
            Assert.IsNotNull(updatedContentKey.AuthorizationPolicyId);
            Assert.AreEqual(policy.Id, updatedContentKey.AuthorizationPolicyId);

            contentKey.AuthorizationPolicyId = null;
            updated = contentKey.UpdateAsync().Result;
            Assert.IsNull(contentKey.AuthorizationPolicyId);
            updatedContentKey = _mediaContext.ContentKeys.Where(c => c.Id == contentKey.Id).FirstOrDefault();
            Assert.IsNull(updatedContentKey.AuthorizationPolicyId);
            contentKey.Delete();
        }
        private static IContentKey CreateKeyWithPolicy(IAsset asset)
        {
            IContentKey key = asset.ContentKeys.Where(k => k.ContentKeyType == ContentKeyType.CommonEncryption).SingleOrDefault();

            if (key != null)
            {
                CleanupKey(key);
                key.Delete();
            }

            var keyId = Guid.NewGuid();

            byte[] contentKey = Guid.NewGuid().ToByteArray();

            ContentKeyType contentKeyType = ContentKeyType.CommonEncryption;
            IContentKeyAuthorizationPolicyOption policyOption;

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

            string configuration = "{}";

            //string configuration = "{\"allowed_track_types\":\"SD_HD\",\"content_key_specs\":[{\"track_type\":\"SD\",\"security_level\":1,\"required_output_protection\":{\"hdcp\":\"HDCP_NONE\"}}],\"policy_overrides\":{\"can_play\":true,\"can_persist\":true,\"can_renew\":false}}";

            policyOption = _mediaContext.ContentKeyAuthorizationPolicyOptions.Create(
                "widevinetest",
                ContentKeyDeliveryType.Widevine,
                restrictions,
                configuration);

            key = _mediaContext.ContentKeys.Create(keyId, contentKey, "TestWidevineKey", contentKeyType);

            var contentKeyAuthorizationPolicy = _mediaContext.ContentKeyAuthorizationPolicies.CreateAsync("test").Result;

            contentKeyAuthorizationPolicy.Options.Add(policyOption);

            key.AuthorizationPolicyId = contentKeyAuthorizationPolicy.Id;
            key = key.UpdateAsync().Result;

            asset.ContentKeys.Add(key);

            return(key);
        }
Example #12
0
        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 ApplyMultiDrmAuthorizationPolicyToAsset(string id)
        {
            IAsset asset = _context.Assets.Where(a => a.Id == id).FirstOrDefault();

            if (asset == null)
            {
                Console.WriteLine("Error: Asset {0} Not Found", id);
            }
            else
            {
                System.Console.WriteLine("Asset Name = {0}", asset.Name);
                DeleteMultiDrmAuthorizationPolicyToAsset(id);

                IContentKey keyCENC = CreateContentKeyCommonType(asset);
                Console.WriteLine("Created CENC key {0} for the asset {1} ", keyCENC.Id, asset.Id);
                Console.WriteLine("PlayReady License Key delivery URL: {0}", keyCENC.GetKeyDeliveryUrl(ContentKeyDeliveryType.PlayReadyLicense));
                Console.WriteLine("Widevine License Key delivery URL: {0}", keyCENC.GetKeyDeliveryUrl(ContentKeyDeliveryType.Widevine));
                IContentKey keyCENCcbcs = CreateContentKeyCommonCBCType(asset);
                Console.WriteLine("Created CENC-cbcs key {0} for the asset {1} ", keyCENCcbcs.Id, asset.Id);
                Console.WriteLine("FairPlay License Key delivery URL: {0}", keyCENCcbcs.GetKeyDeliveryUrl(ContentKeyDeliveryType.FairPlay));
                Console.WriteLine();

                IContentKeyAuthorizationPolicy policyCENC = CreateMultiDrmAuthorizationPolicyCommonType();
                keyCENC.AuthorizationPolicyId = policyCENC.Id;
                keyCENC = keyCENC.UpdateAsync().Result;
                Console.WriteLine("Added authorization policy to CENC Key: {0}", keyCENC.AuthorizationPolicyId);

                IContentKeyAuthorizationPolicy policyCENCcbcs = CreateMultiDrmAuthorizationPolicyCommonCBCType();
                keyCENCcbcs.AuthorizationPolicyId = policyCENCcbcs.Id;
                keyCENCcbcs = keyCENCcbcs.UpdateAsync().Result;
                Console.WriteLine("Added authorization policy to CENC-cbcs Key: {0}", keyCENCcbcs.AuthorizationPolicyId);
                Console.WriteLine();

                CreateAssetDeliveryPolicyCenc(asset, keyCENC);
                CreateAssetDeliveryPolicyCencCbcs(asset, keyCENCcbcs);
                Console.WriteLine("Created asset delivery policy.\n");

                string url = GetStreamingOriginLocator(asset);
                Console.WriteLine("Created locator.");
                Console.WriteLine("Encrypted Smooth+PlayReady URL: {0}/manifest", url);
                Console.WriteLine("Encrypted MPEG-DASH URL: {0}/manifest(format=mpd-time-csf)", url);
                Console.WriteLine("Encrypted HLS+FairPlay URL: {0}/manifest(format=m3u8-aapl)", url);
            }
        }
Example #14
0
        public static string AddTokenRestrictedAuthorizationPolicy(IContentKey contentKey)
        {
            string tokenTemplateString = GenerateTokenRequirements();

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

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

            string WidevineLicenseTemplate = ConfigureWidevineLicenseTemplate();

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

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

            IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = _context.
                                                                           ContentKeyAuthorizationPolicies.
                                                                           CreateAsync("Deliver Common Content Key with token 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;

            return(tokenTemplateString);
        }
Example #15
0
        public static IContentKey AddAuthorizationPolicyToContentKey(CloudMediaContext objCloudMediaContext, IContentKey objIContentKey, string keyId)
        {
            // Create ContentKeyAuthorizationPolicy with restrictions and create authorization policy
            IContentKeyAuthorizationPolicy policy = objCloudMediaContext.ContentKeyAuthorizationPolicies.CreateAsync(keyId).Result;

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

            //ContentKeyAuthorizationPolicyRestriction restriction = new ContentKeyAuthorizationPolicyRestriction
            //                                                                            {
            //                                                                                Name = "Open Authorization Policy",
            //                                                                                KeyRestrictionType = (int)ContentKeyRestrictionType.Open,
            //                                                                                Requirements = null // no requirements
            //                                                                            };
            //ContentKeyAuthorizationPolicyRestriction restriction = new ContentKeyAuthorizationPolicyRestriction
            //{
            //    Name = "Authorization Policy with SWT Token Restriction",
            //    KeyRestrictionType = (int)ContentKeyRestrictionType.TokenRestricted,
            //    Requirements = ContentKeyAuthorizationHelper.CreateRestrictionRequirements()
            //};
            ContentKeyAuthorizationPolicyRestriction restriction = new ContentKeyAuthorizationPolicyRestriction
            {
                Name = "JWTContentKeyAuthorizationPolicyRestriction",
                KeyRestrictionType = (int)ContentKeyRestrictionType.TokenRestricted,
                Requirements       = ContentKeyAuthorizationHelper.CreateRestrictionRequirementsForJWT()
            };

            restrictions.Add(restriction);

            IContentKeyAuthorizationPolicyOption policyOption = objCloudMediaContext.ContentKeyAuthorizationPolicyOptions.Create(
                keyId,
                ContentKeyDeliveryType.BaselineHttp,
                restrictions,
                "");

            policy.Options.Add(policyOption);

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

            return(IContentKeyUpdated);
        }
        private static IContentKey CreateKeyWithPolicy(IAsset asset)
        {
            IContentKey key = asset.ContentKeys.Where(k => k.ContentKeyType == ContentKeyType.CommonEncryptionCbcs).SingleOrDefault();

            if (key != null)
            {
                CleanupKey(key);
            }

            var keyId = Guid.NewGuid();

            byte[] contentKey = Guid.NewGuid().ToByteArray();

            ContentKeyType contentKeyType = ContentKeyType.CommonEncryptionCbcs;
            IContentKeyAuthorizationPolicyOption policyOption;

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

            byte[] iv = Guid.NewGuid().ToByteArray();
            policyOption = CreateFairPlayPolicyOption(iv);

            key = _mediaContext.ContentKeys.Create(keyId, contentKey, "TestFairPlayKey", contentKeyType);

            var contentKeyAuthorizationPolicy = _mediaContext.ContentKeyAuthorizationPolicies.CreateAsync("test").Result;

            contentKeyAuthorizationPolicy.Options.Add(policyOption);

            key.AuthorizationPolicyId = contentKeyAuthorizationPolicy.Id;
            key = key.UpdateAsync().Result;

            asset.ContentKeys.Add(key);

            return(key);
        }
        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;
        }
Example #18
0
        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>();

            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 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;

            Console.WriteLine("Adding Key to Asset: Key ID is " + updatedKey.Id);

            return(tokenTemplateString);
        }
Example #19
0
        public static string AddTokenRestrictedAuthorizationPolicyPlayReady(IContentKey contentKey, Uri Audience, Uri Issuer, CloudMediaContext _context, string newLicenseTemplate)
        {
            string tokenTemplateString = GenerateTokenRequirements(Audience, Issuer);

            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,
                }
            };

            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);
        }
        public static string AddTokenRestrictedAuthorizationPolicy(IContentKey contentKey)
        {
            string tokenTemplateString = GenerateTokenRequirements();

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

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


            IContentKeyAuthorizationPolicyOption FairPlayPolicy =
                _context.ContentKeyAuthorizationPolicyOptions.Create("Token option",
                                                                     ContentKeyDeliveryType.FairPlay,
                                                                     restrictions,
                                                                     FairPlayConfiguration);

            IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = _context.
                                                                           ContentKeyAuthorizationPolicies.
                                                                           CreateAsync("Deliver Common 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);
        }
        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 FairPlay policy option.
            string FairPlayConfiguration = ConfigureFairPlayPolicyOptions();

            IContentKeyAuthorizationPolicyOption FairPlayPolicy =
                _context.ContentKeyAuthorizationPolicyOptions.Create("",
                                                                     ContentKeyDeliveryType.FairPlay,
                                                                     restrictions,
                                                                     FairPlayConfiguration);


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

            contentKeyAuthorizationPolicy.Options.Add(FairPlayPolicy);

            // Associate the content key authorization policy with the content key.
            contentKey.AuthorizationPolicyId = contentKeyAuthorizationPolicy.Id;
            contentKey = contentKey.UpdateAsync().Result;
        }
Example #22
0
        static public IContentKeyAuthorizationPolicy AddOpenAuthorizationPolicy(IContentKey contentKey, ContentKeyDeliveryType contentkeydeliverytype, string keydeliveryconfig, CloudMediaContext _context)
        {
            // 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 = "Open Authorization Policy",
                KeyRestrictionType = (int)ContentKeyRestrictionType.Open,
                Requirements       = null // no requirements needed
            };

            restrictions.Add(restriction);

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

            policy.Options.Add(policyOption);

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

            return(policy);
        }
Example #23
0
        private static IContentKey AddOpenAuthorizationPolicyToContentKey(IContentKey contentKey)
        {
            var policy = _context.ContentKeyAuthorizationPolicies.CreateAsync("Open Authorization Policy").Result;

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

            var policyOption = _context.ContentKeyAuthorizationPolicyOptions.
                               Create("Authorization Policy Option", ContentKeyDeliveryType.BaselineHttp, restrictions, string.Empty);

            policy.Options.Add(policyOption);

            contentKey.AuthorizationPolicyId = policy.Id;
            var updatedKey = contentKey.UpdateAsync().Result;

            return(updatedKey);
        }
        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;
        }
Example #25
0
        public static async Task <object> Run([HttpTrigger(WebHookType = "genericJson")] HttpRequestMessage req, TraceWriter log)
        {
            log.Info($"AMS v2 Function - Add Dynamic Encryption was triggered!");

            string jsonContent = await req.Content.ReadAsStringAsync();

            dynamic data = JsonConvert.DeserializeObject(jsonContent);

            // Validate input objects
            if (data.assetId == null && data.programId == null && data.channelName == null && data.programName == null)
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Please pass assetId or programID or channelName/programName in the input object" }));
            }

            if (data.contentKeyAuthorizationPolicyId == null)
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Please pass contentKeyAuthorizationPolicyId in the input object" }));
            }

            if (data.assetDeliveryPolicyId == null)
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Please pass assetDeliveryPolicyId in the input object" }));
            }

            if (data.contentKeyType == null)
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Please pass contentKeyType in the input object" }));
            }

            string assetId     = data.assetId;
            string programId   = data.programId;
            string channelName = data.channelName;
            string programName = data.programName;
            string contentKeyAuthorizationPolicyId = data.contentKeyAuthorizationPolicyId;
            string assetDeliveryPolicyId           = data.assetDeliveryPolicyId;
            string contentKeyTypeName = data.contentKeyType;
            string contentKeyId       = data.keyId;
            string contentKeySecret   = data.contentKey;

            if (!MediaServicesHelper.AMSContentKeyType.ContainsKey(contentKeyTypeName))
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Please pass a valid contentKeyType in the input object" }));
            }


            ContentKeyType contentKeyType = MediaServicesHelper.AMSContentKeyType[contentKeyTypeName];

            if (contentKeyType != ContentKeyType.CommonEncryption && contentKeyType != ContentKeyType.CommonEncryptionCbcs && contentKeyType != ContentKeyType.EnvelopeEncryption)
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Please pass a valid contentKeyType in the input object" }));
            }


            string contentKeyName = null;

            if (data.contentKeyName != null)
            {
                contentKeyName = data.contentKeyName;
            }

            MediaServicesCredentials amsCredentials = new MediaServicesCredentials();
            IAsset asset = null;
            IContentKeyAuthorizationPolicy ckaPolicy = null;
            IAssetDeliveryPolicy           adPolicy  = null;
            IContentKey contentKey = null;

            try
            {
                // Load AMS account context
                log.Info($"Using AMS v2 REST API Endpoint : {amsCredentials.AmsRestApiEndpoint.ToString()}");

                AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(amsCredentials.AmsAadTenantDomain,
                                                                                       new AzureAdClientSymmetricKey(amsCredentials.AmsClientId, amsCredentials.AmsClientSecret),
                                                                                       AzureEnvironments.AzureCloudEnvironment);
                AzureAdTokenProvider tokenProvider = new AzureAdTokenProvider(tokenCredentials);
                _context = new CloudMediaContext(amsCredentials.AmsRestApiEndpoint, tokenProvider);

                // Let's get the asset
                if (assetId != null)
                {
                    // Get the Asset, ContentKeyAuthorizationPolicy, AssetDeliveryPolicy
                    asset = _context.Assets.Where(a => a.Id == assetId).FirstOrDefault();
                    if (asset == null)
                    {
                        return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Asset not found" }));
                    }
                }
                else if (programId != null)
                {
                    var program = _context.Programs.Where(p => p.Id == programId).FirstOrDefault();
                    if (program == null)
                    {
                        log.Info("Program not found");
                        return(req.CreateResponse(HttpStatusCode.BadRequest, new
                        {
                            error = "Program not found"
                        }));
                    }
                    asset = program.Asset;
                }
                else // with channelName and programName
                {
                    // find the Channel, Program and Asset
                    var channel = _context.Channels.Where(c => c.Name == channelName).FirstOrDefault();
                    if (channel == null)
                    {
                        log.Info("Channel not found");
                        return(req.CreateResponse(HttpStatusCode.BadRequest, new
                        {
                            error = "Channel not found"
                        }));
                    }

                    var program = channel.Programs.Where(p => p.Name == programName).FirstOrDefault();
                    if (program == null)
                    {
                        log.Info("Program not found");
                        return(req.CreateResponse(HttpStatusCode.BadRequest, new
                        {
                            error = "Program not found"
                        }));
                    }
                    asset = program.Asset;
                }

                log.Info($"Using asset Id : {asset.Id}");

                ckaPolicy = _context.ContentKeyAuthorizationPolicies.Where(p => p.Id == contentKeyAuthorizationPolicyId).Single();
                if (ckaPolicy == null)
                {
                    return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "ContentKeyAuthorizationPolicy not found" }));
                }
                adPolicy = _context.AssetDeliveryPolicies.Where(p => p.Id == assetDeliveryPolicyId).Single();
                if (adPolicy == null)
                {
                    return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "AssetDeliveryPolicy not found" }));
                }

                if (contentKeyId != null)
                {
                    string keyiddwitprefix = "";

                    if (contentKeyId.StartsWith("nb:kid:UUID:"))
                    {
                        keyiddwitprefix = contentKeyId;
                        contentKeyId    = contentKeyId.Substring(12);
                    }
                    else
                    {
                        keyiddwitprefix = "nb:kid:UUID:" + contentKeyId;
                    }

                    // let's retrieve the key if it exists already
                    contentKey = _context.ContentKeys.Where(k => k.Id == keyiddwitprefix).FirstOrDefault();
                }

                if (contentKey == null) // let's create it as it was not found or delivered to the function
                {
                    switch (contentKeyType)
                    {
                    case ContentKeyType.CommonEncryption:
                        if (contentKeyName == null)
                        {
                            contentKeyName = "Common Encryption ContentKey";
                        }
                        contentKey = MediaServicesHelper.CreateContentKey(_context, contentKeyName, ContentKeyType.CommonEncryption, contentKeyId, contentKeySecret);
                        break;

                    case ContentKeyType.CommonEncryptionCbcs:
                        if (contentKeyName == null)
                        {
                            contentKeyName = "Common Encryption CBCS ContentKey";
                        }
                        contentKey = MediaServicesHelper.CreateContentKey(_context, contentKeyName, ContentKeyType.CommonEncryptionCbcs, contentKeyId, contentKeySecret);
                        break;

                    case ContentKeyType.EnvelopeEncryption:
                        if (contentKeyName == null)
                        {
                            contentKeyName = "Envelope Encryption ContentKey";
                        }
                        contentKey = MediaServicesHelper.CreateContentKey(_context, contentKeyName, ContentKeyType.EnvelopeEncryption, contentKeyId, contentKeySecret);
                        break;
                    }
                }

                asset.ContentKeys.Add(contentKey);
                contentKey.AuthorizationPolicyId = ckaPolicy.Id;
                contentKey = contentKey.UpdateAsync().Result;
                asset.DeliveryPolicies.Add(adPolicy);
            }
            catch (Exception ex)
            {
                string message = ex.Message + ((ex.InnerException != null) ? Environment.NewLine + MediaServicesHelper.GetErrorMessage(ex) : "");
                log.Info($"ERROR: Exception {message}");
                return(req.CreateResponse(HttpStatusCode.InternalServerError, new { error = message }));
            }

            return(req.CreateResponse(HttpStatusCode.OK, new
            {
                contentKeyId = contentKey.Id,
                assetId = asset.Id
            }));
        }
        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);
        }
        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 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;
        }
        public static async Task <object> Run([HttpTrigger(WebHookType = "genericJson")] HttpRequestMessage req, TraceWriter log)
        {
            log.Info($"AMS v2 Function - CreateContentKeyAuthorizationPolicy was triggered!");

            string jsonContent = await req.Content.ReadAsStringAsync();

            dynamic data = JsonConvert.DeserializeObject(jsonContent);

            // Validate input objects
            if (data.assetId == null)
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Please pass assetId in the input object" }));
            }
            if (data.contentKeyAuthorizationPolicyId == null)
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Please pass contentKeyAuthorizationPolicyId in the input object" }));
            }
            if (data.assetDeliveryPolicyId == null)
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Please pass assetDeliveryPolicyId in the input object" }));
            }
            if (data.contentKeyType == null)
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Please pass contentKeyType in the input object" }));
            }
            string assetId = data.assetId;
            string contentKeyAuthorizationPolicyId = data.contentKeyAuthorizationPolicyId;
            string assetDeliveryPolicyId           = data.assetDeliveryPolicyId;
            string contentKeyTypeName = data.contentKeyType;

            if (!MediaServicesHelper.AMSContentKeyType.ContainsKey(contentKeyTypeName))
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Please pass a valid contentKeyType in the input object" }));
            }
            ContentKeyType contentKeyType = MediaServicesHelper.AMSContentKeyType[contentKeyTypeName];

            if (contentKeyType != ContentKeyType.CommonEncryption && contentKeyType != ContentKeyType.CommonEncryptionCbcs && contentKeyType != ContentKeyType.EnvelopeEncryption)
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Please pass a valid contentKeyType in the input object" }));
            }
            string contentKeyName = null;

            if (data.contentKeyName != null)
            {
                contentKeyName = data.contentKeyName;
            }

            MediaServicesCredentials amsCredentials = new MediaServicesCredentials();
            IAsset asset = null;
            IContentKeyAuthorizationPolicy ckaPolicy = null;
            IAssetDeliveryPolicy           adPolicy  = null;
            IContentKey contentKey = null;

            try
            {
                // Load AMS account context
                log.Info($"Using AMS v2 REST API Endpoint : {amsCredentials.AmsRestApiEndpoint.ToString()}");

                AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(amsCredentials.AmsAadTenantDomain,
                                                                                       new AzureAdClientSymmetricKey(amsCredentials.AmsClientId, amsCredentials.AmsClientSecret),
                                                                                       AzureEnvironments.AzureCloudEnvironment);
                AzureAdTokenProvider tokenProvider = new AzureAdTokenProvider(tokenCredentials);
                _context = new CloudMediaContext(amsCredentials.AmsRestApiEndpoint, tokenProvider);

                // Get the Asset, ContentKeyAuthorizationPolicy, AssetDeliveryPolicy
                asset = _context.Assets.Where(a => a.Id == assetId).FirstOrDefault();
                if (asset == null)
                {
                    return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Asset not found" }));
                }
                ckaPolicy = _context.ContentKeyAuthorizationPolicies.Where(p => p.Id == contentKeyAuthorizationPolicyId).Single();
                if (ckaPolicy == null)
                {
                    return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "ContentKeyAuthorizationPolicy not found" }));
                }
                adPolicy = _context.AssetDeliveryPolicies.Where(p => p.Id == assetDeliveryPolicyId).Single();
                if (adPolicy == null)
                {
                    return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "AssetDeliveryPolicy not found" }));
                }
                switch (contentKeyType)
                {
                case ContentKeyType.CommonEncryption:
                    if (contentKeyName == null)
                    {
                        contentKeyName = "Common Encryption ContentKey";
                    }
                    contentKey = MediaServicesHelper.CreateContentKey(_context, contentKeyName, ContentKeyType.CommonEncryption);
                    break;

                case ContentKeyType.CommonEncryptionCbcs:
                    if (contentKeyName == null)
                    {
                        contentKeyName = "Common Encryption CBCS ContentKey";
                    }
                    contentKey = MediaServicesHelper.CreateContentKey(_context, contentKeyName, ContentKeyType.CommonEncryptionCbcs);
                    break;

                case ContentKeyType.EnvelopeEncryption:
                    if (contentKeyName == null)
                    {
                        contentKeyName = "Envelope Encryption ContentKey";
                    }
                    contentKey = MediaServicesHelper.CreateContentKey(_context, contentKeyName, ContentKeyType.EnvelopeEncryption);
                    break;
                }
                asset.ContentKeys.Add(contentKey);
                contentKey.AuthorizationPolicyId = ckaPolicy.Id;
                contentKey = contentKey.UpdateAsync().Result;
                asset.DeliveryPolicies.Add(adPolicy);
            }
            catch (Exception e)
            {
                log.Info($"ERROR: Exception {e}");
                return(req.CreateResponse(HttpStatusCode.BadRequest));
            }

            return(req.CreateResponse(HttpStatusCode.OK, new
            {
                contentKeyId = contentKey.Id
            }));
        }
        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;
        }
 private static void UpdateDeleteContentKey(IContentKey key)
 {
     key.AuthorizationPolicyId = Guid.NewGuid().ToString();
     key.Update();
     key.AuthorizationPolicyId = Guid.NewGuid().ToString();
     key.UpdateAsync();
     key.Delete();
 }
        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;
        }
Example #33
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;
        }