/// <summary>
        /// Deserializes a string containing an Xml representation of a TokenRestrictionTemplate
        /// back into a TokenRestrictionTemplate class instance.
        /// </summary>
        /// <param name="templateXml">A string containing the Xml representation of a TokenRestrictionTemplate</param>
        /// <returns>TokenRestrictionTemplate instance</returns>
        public static TokenRestrictionTemplate Deserialize(string templateXml)
        {
            TokenRestrictionTemplate templateToReturn = null;
            DataContractSerializer   serializer       = GetSerializer();

            StringReader stringReader = null;
            XmlReader    reader       = null;

            try
            {
                stringReader = new StringReader(templateXml);

                reader = XmlReader.Create(stringReader);

                templateToReturn = (TokenRestrictionTemplate)serializer.ReadObject(reader);
            }
            finally
            {
                if (reader != null)
                {
                    // This will close the underlying StringReader instance
                    reader.Close();
                }
                else if (stringReader != null)
                {
                    stringReader.Close();
                }
            }

            if (templateToReturn.PrimaryVerificationKey == null && templateToReturn.OpenIdConnectDiscoveryDocument == null)
            {
                throw new InvalidDataContractException(StringTable.PrimaryVerificationKeyAndOpenIdConnectDiscoveryDocumentAreNull);
            }

            if (templateToReturn.OpenIdConnectDiscoveryDocument != null && String.IsNullOrEmpty(templateToReturn.OpenIdConnectDiscoveryDocument.OpenIdDiscoveryUri))
            {
                throw new InvalidDataContractException(String.Format(CultureInfo.InvariantCulture, StringTable.ArgumentStringIsNullOrEmpty, "OpenIdConnectDiscoveryDocument.OpenIdDiscoveryUri"));
            }

            Uri openIdDiscoveryUri;

            if (templateToReturn.OpenIdConnectDiscoveryDocument != null && !Uri.TryCreate(templateToReturn.OpenIdConnectDiscoveryDocument.OpenIdDiscoveryUri, UriKind.Absolute, out openIdDiscoveryUri))
            {
                throw new InvalidDataContractException(String.Format(CultureInfo.InvariantCulture, StringTable.StringIsNotAbsoluteUri, "OpenIdConnectDiscoveryDocument.OpenIdDiscoveryUri"));
            }


            return(templateToReturn);
        }
        /// <summary>
        /// Used to generate a test token based on the the data in the given TokenRestrictionTemplate.
        /// </summary>
        /// <param name="tokenTemplate">TokenRestrictionTemplate describing the token to generate</param>
        /// <param name="signingKeyToUse">Specifies the specific signing key to use.  If null, the PrimaryVerificationKey from the template is used.</param>
        /// <param name="keyIdForContentKeyIdentifierClaim">Key Identifier used as the value of the Content Key Identifier Claim.  Ignored if no TokenClaim with a ClaimType of TokenClaim.ContentKeyIdentifierClaimType is not present</param>
        /// <param name="tokenExpiration">The Date and Time when the token expires.  Expired tokens are considered invalid by the Key Delivery Service.</param>
        /// <returns>A Simple Web Token (SWT)</returns>
        public static string GenerateTestToken(TokenRestrictionTemplate tokenTemplate, TokenVerificationKey signingKeyToUse = null, Guid?keyIdForContentKeyIdentifierClaim = null, DateTime?tokenExpiration = null)
        {
            if (tokenTemplate == null)
            {
                throw new ArgumentNullException("tokenTemplate");
            }

            if (signingKeyToUse == null)
            {
                signingKeyToUse = tokenTemplate.PrimaryVerificationKey;
            }

            if (!tokenExpiration.HasValue)
            {
                tokenExpiration = DateTime.UtcNow.AddMinutes(10);
            }

            StringBuilder builder = new StringBuilder();

            foreach (TokenClaim claim in tokenTemplate.RequiredClaims)
            {
                string claimValue = claim.ClaimValue;
                if (claim.ClaimType == TokenClaim.ContentKeyIdentifierClaimType)
                {
                    claimValue = keyIdForContentKeyIdentifierClaim.ToString();
                }

                builder.AppendFormat("{0}={1}&", HttpUtility.UrlEncode(claim.ClaimType), HttpUtility.UrlEncode(claimValue));
            }

            builder.AppendFormat("Audience={0}&", HttpUtility.UrlEncode(tokenTemplate.Audience));
            builder.AppendFormat("ExpiresOn={0}&", GenerateTokenExpiry(tokenExpiration.Value));
            builder.AppendFormat("Issuer={0}", HttpUtility.UrlEncode(tokenTemplate.Issuer));

            SymmetricVerificationKey signingKey = (SymmetricVerificationKey)signingKeyToUse;

            using (var signatureAlgorithm = new HMACSHA256(signingKey.KeyValue))
            {
                byte[] unsignedTokenAsBytes = Encoding.UTF8.GetBytes(builder.ToString());

                byte[] signatureBytes = signatureAlgorithm.ComputeHash(unsignedTokenAsBytes);

                string signatureString = Convert.ToBase64String(signatureBytes);

                builder.AppendFormat("&HMACSHA256={0}", HttpUtility.UrlEncode(signatureString));
            }

            return(builder.ToString());
        }
        /// <summary>
        /// Used to generate a test token based on the the data in the given TokenRestrictionTemplate.
        /// </summary>
        /// <param name="tokenTemplate">TokenRestrictionTemplate describing the token to generate</param>
        /// <param name="signingKeyToUse">Specifies the specific signing key to use.  If null, the PrimaryVerificationKey from the template is used.</param>
        /// <param name="keyIdForContentKeyIdentifierClaim">Key Identifier used as the value of the Content Key Identifier Claim.  Ignored if no TokenClaim with a ClaimType of TokenClaim.ContentKeyIdentifierClaimType is not present</param>
        /// <param name="tokenExpiration">The Date and Time when the token expires.  Expired tokens are considered invalid by the Key Delivery Service.</param>
        /// <returns>A Simple Web Token (SWT)</returns>
        public static string GenerateTestToken(TokenRestrictionTemplate tokenTemplate, TokenVerificationKey signingKeyToUse = null, Guid? keyIdForContentKeyIdentifierClaim = null, DateTime? tokenExpiration = null)
        {
            if (tokenTemplate == null)
            {
                throw new ArgumentNullException("tokenTemplate");
            }

            if (signingKeyToUse == null)
            {
                signingKeyToUse = tokenTemplate.PrimaryVerificationKey;
            }

            if (!tokenExpiration.HasValue)
            {
                tokenExpiration = DateTime.UtcNow.AddMinutes(10);
            }

            StringBuilder builder = new StringBuilder();

            foreach (TokenClaim claim in tokenTemplate.RequiredClaims)
            {
                string claimValue = claim.ClaimValue;
                if (claim.ClaimType == TokenClaim.ContentKeyIdentifierClaimType)
                {
                    claimValue = keyIdForContentKeyIdentifierClaim.ToString();
                }

                builder.AppendFormat("{0}={1}&", HttpUtility.UrlEncode(claim.ClaimType), HttpUtility.UrlEncode(claimValue));
            }

            builder.AppendFormat("Audience={0}&", HttpUtility.UrlEncode(tokenTemplate.Audience.AbsoluteUri));
            builder.AppendFormat("ExpiresOn={0}&", GenerateTokenExpiry(tokenExpiration.Value));
            builder.AppendFormat("Issuer={0}", HttpUtility.UrlEncode(tokenTemplate.Issuer.AbsoluteUri));

            SymmetricVerificationKey signingKey = (SymmetricVerificationKey)signingKeyToUse;
            using (var signatureAlgorithm = new HMACSHA256(signingKey.KeyValue))
            {
                byte[] unsignedTokenAsBytes = Encoding.UTF8.GetBytes(builder.ToString());

                byte[] signatureBytes = signatureAlgorithm.ComputeHash(unsignedTokenAsBytes);

                string signatureString = Convert.ToBase64String(signatureBytes);

                builder.Insert(0, "Bearer=");
                builder.AppendFormat("&HMACSHA256={0}", HttpUtility.UrlEncode(signatureString));
            }

            return builder.ToString();
        }
        public void AddingOptionsToCreatedPolicy()
        {
            string optionName = "AddingOptionsToCreatedPolicy Test Option";

            PlayReadyLicenseResponseTemplate responseTemplate = new PlayReadyLicenseResponseTemplate();
            responseTemplate.LicenseTemplates.Add(new PlayReadyLicenseTemplate());

            TokenRestrictionTemplate tokenRestrictionTemplate = new TokenRestrictionTemplate(TokenType.JWT);
            tokenRestrictionTemplate.PrimaryVerificationKey = new SymmetricVerificationKey(); // the default constructor automatically generates a random key
            tokenRestrictionTemplate.Audience = "urn:someaudience";
            tokenRestrictionTemplate.Issuer = "http://someissuerurl";

            string requirements = TokenRestrictionTemplateSerializer.Serialize(tokenRestrictionTemplate);
            string configuration = MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);

            ContentKeyRestrictionType restrictionType = ContentKeyRestrictionType.TokenRestricted;

            IContentKeyAuthorizationPolicy policy = _mediaContext.ContentKeyAuthorizationPolicies.CreateAsync(testRun).Result;
            var option1 = ContentKeyAuthorizationPolicyOptionTests.CreateOption(_mediaContext, optionName, ContentKeyDeliveryType.PlayReadyLicense, requirements, configuration, restrictionType);
            policy.Options.Add(option1);
        }
        /// <summary>
        /// Serializes a TokenRestrictionTemplate to a string containing an xml representation of
        /// the token restriction template.
        /// </summary>
        /// <param name="template">TokenRestrictionTemplate instance to serialize to a string</param>
        /// <returns>An xml string representation of the TokenRestrictionTemplate instance</returns>
        public static string Serialize(TokenRestrictionTemplate template)
        {
            if (template.PrimaryVerificationKey == null &&
                template.OpenIdConnectDiscoveryDocument == null)
            {
                throw new InvalidDataContractException(StringTable.PrimaryVerificationKeyAndOpenIdConnectDiscoveryDocumentAreNull);
            }

            if (template.OpenIdConnectDiscoveryDocument != null &&
                String.IsNullOrEmpty(template.OpenIdConnectDiscoveryDocument.OpenIdDiscoveryUri))
            {
                throw new InvalidDataContractException(String.Format(CultureInfo.InvariantCulture, StringTable.ArgumentStringIsNullOrEmpty, "OpenIdDiscoveryUri"));
            }

            Uri openIdDiscoveryUri;

            if (template.OpenIdConnectDiscoveryDocument != null && !Uri.TryCreate(template.OpenIdConnectDiscoveryDocument.OpenIdDiscoveryUri, UriKind.Absolute, out openIdDiscoveryUri))
            {
                throw new InvalidDataContractException(String.Format(CultureInfo.InvariantCulture, StringTable.StringIsNotAbsoluteUri, "OpenIdConnectDiscoveryDocument.OpenIdDiscoveryUri"));
            }



            DataContractSerializer serializer = GetSerializer();

            if (template.TokenType == TokenType.SWT)
            {
                if (!Uri.IsWellFormedUriString(template.Issuer, UriKind.Absolute))
                {
                    throw new InvalidDataContractException(String.Format(CultureInfo.InvariantCulture, StringTable.InvalidAbsoluteUriInSWTToken, "template.Issuer"));
                }
                if (!Uri.IsWellFormedUriString(template.Audience, UriKind.Absolute))
                {
                    throw new InvalidDataContractException(String.Format(CultureInfo.InvariantCulture, StringTable.InvalidAbsoluteUriInSWTToken, "template.Audience"));
                }
            }

            return(MediaServicesLicenseTemplateSerializer.SerializeToXml(template, serializer));
        }
        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;
        }
        static private string GenerateTokenRequirements()
        {
            TokenRestrictionTemplate template = new TokenRestrictionTemplate(TokenType.SWT);

            template.PrimaryVerificationKey = new SymmetricVerificationKey();
            template.AlternateVerificationKeys.Add(new SymmetricVerificationKey());
            template.Audience = _sampleAudience;
            template.Issuer = _sampleIssuer;
            template.RequiredClaims.Add(TokenClaim.ContentKeyIdentifierClaim);

            return TokenRestrictionTemplateSerializer.Serialize(template);
        } 
 private string GenerateTokenRequirements()
 {
     //TokenRestrictionTemplate template = new TokenRestrictionTemplate();
     //template.PrimaryVerificationKey = new SymmetricVerificationKey();
     //template.AlternateVerificationKeys.Add(new SymmetricVerificationKey());
     //template.Audience = new Uri( myConfig.sampleAudience);
     //template.Issuer = new Uri( myConfig.sampleIssuer) ;
     //template.RequiredClaims.Add(TokenClaim.ContentKeyIdentifierClaim);
     //return TokenRestrictionTemplateSerializer.Serialize(template);
     string primarySymmetricKey = "8sAEcbUnsHJOnMpRU0f7z4gAROCoQ3ailkK5ARIt12iDxOu5KTf5mihIbims0uJHTTQQSkO/W+WDTEdFFH7rug==";
     string secondarySymmetricKey = "vga/o4PJT+IQAaH1Po0uhBrL7aoUu0prBTO9jmWsk71CFtPwBJiwwBiWMN45NGXp3rDIIi81E3QU0dXg7pmDxw==";
     TokenRestrictionTemplate objTokenRestrictionTemplate = new TokenRestrictionTemplate();
     objTokenRestrictionTemplate.PrimaryVerificationKey = new SymmetricVerificationKey(Convert.FromBase64String(primarySymmetricKey));
     objTokenRestrictionTemplate.AlternateVerificationKeys.Add(new SymmetricVerificationKey(Convert.FromBase64String(secondarySymmetricKey)));
     objTokenRestrictionTemplate.Audience = new Uri(myConfig.sampleAudience);
     objTokenRestrictionTemplate.Issuer = new Uri(myConfig.sampleIssuer);
     return TokenRestrictionTemplateSerializer.Serialize(objTokenRestrictionTemplate);
 }
        private void FetchKeyWithSWTToken(string audience, string issuer)
        {
            IContentKey contentKey = null;
            IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = null;
            IContentKeyAuthorizationPolicyOption policyOption = null;

            try
            {
                byte[] expectedKey = null;
                contentKey = CreateTestKey(_mediaContext, ContentKeyType.EnvelopeEncryption, out expectedKey);

                var contentKeyId = Guid.Parse(contentKey.Id.Replace("nb:kid:UUID:", String.Empty));

                TokenRestrictionTemplate tokenRestrictionTemplate = new TokenRestrictionTemplate(TokenType.SWT);
                tokenRestrictionTemplate.PrimaryVerificationKey = new SymmetricVerificationKey();
                    // the default constructor automatically generates a random key

                tokenRestrictionTemplate.Audience = audience;
                tokenRestrictionTemplate.Issuer = issuer;
                tokenRestrictionTemplate.TokenType = TokenType.SWT;
                tokenRestrictionTemplate.RequiredClaims.Add(new TokenClaim(TokenClaim.ContentKeyIdentifierClaimType,
                    contentKeyId.ToString()));

                string optionName = "GetHlsKeyDeliveryUrlAndFetchKeyWithSWTAuthentication";
                string requirements = TokenRestrictionTemplateSerializer.Serialize(tokenRestrictionTemplate);
                ContentKeyRestrictionType restrictionType = ContentKeyRestrictionType.TokenRestricted;
                var _testOption = ContentKeyAuthorizationPolicyOptionTests.CreateOption(_mediaContext, optionName,
                    ContentKeyDeliveryType.BaselineHttp, requirements, null, restrictionType);

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

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

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

                Assert.IsNotNull(keyDeliveryServiceUri);

                Assert.IsTrue(keyDeliveryServiceUri.Host.StartsWith(_mediaContext.Credentials.ClientId));

                KeyDeliveryServiceClient keyClient = new KeyDeliveryServiceClient(RetryPolicy.DefaultFixed);
                string swtTokenString = TokenRestrictionTemplateSerializer.GenerateTestToken(tokenRestrictionTemplate,
                    tokenRestrictionTemplate.PrimaryVerificationKey, contentKeyId, DateTime.Now.AddDays(2));
                byte[] key = keyClient.AcquireHlsKeyWithBearerHeader(keyDeliveryServiceUri, swtTokenString);

                string expectedString = GetString(expectedKey);
                string fetchedString = GetString(key);
                Assert.AreEqual(expectedString, fetchedString);
            }
            finally
            {
                CleanupKeyAndPolicy(contentKey, contentKeyAuthorizationPolicy, policyOption);
            }
        }
        public void GetHlsKeyDeliveryUrlAndFetchKeyWithADJWTAuthUsingADOpenConnectDiscovery()
        {
            //
            // The Client ID is used by the application to uniquely identify itself to Azure AD.
            // The App Key is a credential used by the application to authenticate to Azure AD.
            // The Tenant is the name of the Azure AD tenant in which this application is registered.
            // The AAD Instance is the instance of Azure, for example public Azure or Azure China.
            // The Authority is the sign-in URL of the tenant.
            //
            string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
            string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
            string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
            string appKey = ConfigurationManager.AppSettings["ida:AppKey"];

            string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

            //
            // To authenticate to the To Do list service, the client needs to know the service's App ID URI.
            // To contact the To Do list service we need it's URL as well.
            //
            string appResourceId = ConfigurationManager.AppSettings["app:AppResourceId"];

            IContentKey contentKey = null;
            IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = null;
            IContentKeyAuthorizationPolicyOption policyOption = null;

            var authContext = new AuthenticationContext(authority);
            var clientCredential = new ClientCredential(clientId, appKey);

            try
            {
                byte[] expectedKey = null;
                contentKey = CreateTestKey(_mediaContext, ContentKeyType.EnvelopeEncryption, out expectedKey, "GetHlsKeyDeliveryUrlAndFetchKeyWithADJWTAuthUsingADOpenConnectDiscovery"+Guid.NewGuid().ToString());

                TokenRestrictionTemplate tokenRestrictionTemplate = new TokenRestrictionTemplate(TokenType.JWT);
                tokenRestrictionTemplate.OpenIdConnectDiscoveryDocument = new OpenIdConnectDiscoveryDocument("https://login.windows.net/common/.well-known/openid-configuration");
                var result = authContext.AcquireToken(appResourceId, clientCredential);
                string jwtTokenString = result.AccessToken;

                JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
                Assert.IsTrue(handler.CanReadToken(jwtTokenString));
                JwtSecurityToken token = handler.ReadToken(jwtTokenString) as JwtSecurityToken;
                Assert.IsNotNull(token);

                tokenRestrictionTemplate.Audience =  token.Audiences.First();
                tokenRestrictionTemplate.Issuer = token.Issuer;

                string optionName = "GetHlsKeyDeliveryUrlAndFetchKeyWithJWTAuthentication";
                string requirements = TokenRestrictionTemplateSerializer.Serialize(tokenRestrictionTemplate);
                policyOption = ContentKeyAuthorizationPolicyOptionTests.CreateOption(_mediaContext, optionName, ContentKeyDeliveryType.BaselineHttp, requirements, null, ContentKeyRestrictionType.TokenRestricted);

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

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

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

                // Enable once all accounts are enabled for per customer Key Delivery Urls
                //Assert.IsTrue(keyDeliveryServiceUri.Host.StartsWith(_mediaContext.Credentials.ClientId));

                KeyDeliveryServiceClient keyClient = new KeyDeliveryServiceClient(RetryPolicy.DefaultFixed);
                byte[] key = keyClient.AcquireHlsKeyWithBearerHeader(keyDeliveryServiceUri, jwtTokenString);

                string expectedString = GetString(expectedKey);
                string fetchedString = GetString(key);
                Assert.AreEqual(expectedString, fetchedString);
            }
            finally
            {
                CleanupKeyAndPolicy(contentKey, contentKeyAuthorizationPolicy, policyOption);
            }
        }
        public void RoundTripTest()
        {
            TokenRestrictionTemplate template = new TokenRestrictionTemplate();

            template.PrimaryVerificationKey = new SymmetricVerificationKey();
            template.AlternateVerificationKeys.Add(new SymmetricVerificationKey());
            template.Audience = _sampleAudience;
            template.Issuer = _sampleIssuer;
            template.RequiredClaims.Add(TokenClaim.ContentKeyIdentifierClaim);
            template.RequiredClaims.Add(new TokenClaim("Rental", "true"));

            string serializedTemplate = TokenRestrictionTemplateSerializer.Serialize(template);
            Assert.IsFalse(String.IsNullOrWhiteSpace(serializedTemplate));

            TokenRestrictionTemplate template2 = TokenRestrictionTemplateSerializer.Deserialize(serializedTemplate);
            Assert.IsNotNull(template2);
            Assert.AreEqual(template.Issuer, template2.Issuer);
            Assert.AreEqual(template.Audience, template2.Audience);

            SymmetricVerificationKey fromTemplate = (SymmetricVerificationKey) template.PrimaryVerificationKey;
            SymmetricVerificationKey fromTemplate2 = (SymmetricVerificationKey) template2.PrimaryVerificationKey;

            Assert.IsTrue(fromTemplate.KeyValue.SequenceEqual(fromTemplate2.KeyValue));
        }
        /// <summary>
        /// Serializes a TokenRestrictionTemplate to a string containing an xml representation of
        /// the token restriction template.
        /// </summary>
        /// <param name="template">TokenRestrictionTemplate instance to serialize to a string</param>
        /// <returns>An xml string representation of the TokenRestrictionTemplate instance</returns>
        public static string Serialize(TokenRestrictionTemplate template)
        {
            if (template.PrimaryVerificationKey == null &&
                template.OpenIdConnectDiscoveryDocument == null)
            {
                throw new InvalidDataContractException(StringTable.PrimaryVerificationKeyAndOpenIdConnectDiscoveryDocumentAreNull);
            }

            if (template.OpenIdConnectDiscoveryDocument != null &&
                String.IsNullOrEmpty(template.OpenIdConnectDiscoveryDocument.OpenIdDiscoveryUri))
            {
                throw new InvalidDataContractException(String.Format(CultureInfo.InvariantCulture,StringTable.ArgumentStringIsNullOrEmpty,"OpenIdDiscoveryUri"));
            }

            Uri openIdDiscoveryUri;
            if (template.OpenIdConnectDiscoveryDocument != null && !Uri.TryCreate(template.OpenIdConnectDiscoveryDocument.OpenIdDiscoveryUri, UriKind.Absolute, out openIdDiscoveryUri))
            {
                throw new InvalidDataContractException(String.Format(CultureInfo.InvariantCulture, StringTable.StringIsNotAbsoluteUri, "OpenIdConnectDiscoveryDocument.OpenIdDiscoveryUri"));
            }

            DataContractSerializer serializer = GetSerializer();

            if (template.TokenType == TokenType.SWT)
            {
                if (!Uri.IsWellFormedUriString(template.Issuer, UriKind.Absolute))
                {
                    throw new InvalidDataContractException(String.Format(CultureInfo.InvariantCulture, StringTable.InvalidAbsoluteUriInSWTToken,"template.Issuer"));
                }
                if (!Uri.IsWellFormedUriString(template.Audience, UriKind.Absolute))
                {
                    throw new InvalidDataContractException(String.Format(CultureInfo.InvariantCulture, StringTable.InvalidAbsoluteUriInSWTToken,"template.Audience"));
                }
            }

            return MediaServicesLicenseTemplateSerializer.SerializeToXml(template, serializer);
        }
        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;
        }
 private static string GenerateTokenRequirements(TokenType mytokentype, string _sampleAudience, string _sampleIssuer, IList<TokenClaim> tokenclaimslist, bool AddContentKeyIdentifierClaim, TokenVerificationKey mytokenverificationkey)
 {
     TokenRestrictionTemplate TokenrestrictionTemplate = new TokenRestrictionTemplate(mytokentype)
     {
         PrimaryVerificationKey = mytokenverificationkey,
         Audience = _sampleAudience,
         Issuer = _sampleIssuer
     };
     if (AddContentKeyIdentifierClaim) TokenrestrictionTemplate.RequiredClaims.Add(TokenClaim.ContentKeyIdentifierClaim);
     foreach (var t in tokenclaimslist)
     {
         TokenrestrictionTemplate.RequiredClaims.Add(t);
     }
     return TokenRestrictionTemplateSerializer.Serialize(TokenrestrictionTemplate);
 }
        /// <summary>
        /// Serializes a TokenRestrictionTemplate to a string containing an xml representation of
        /// the token restriction template.
        /// </summary>
        /// <param name="template">TokenRestrictionTemplate instance to serialize to a string</param>
        /// <returns>An xml string representation of the TokenRestrictionTemplate instance</returns>
        public static string Serialize(TokenRestrictionTemplate template)
        {
            DataContractSerializer serializer = GetSerializer();

            return(MediaServicesLicenseTemplateSerializer.SerializeToXml(template, serializer));
        }
        public void FetchKeyWithRSATokenValidationKeyAsPrimaryVerificationKey()
        {
            //Create a new RSACryptoServiceProvider object.
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {
                //Export the key information to an RSAParameters object.
                //Pass false to export the public key information or pass
                //true to export public and private key information.
                RSAParameters RSAParams = RSA.ExportParameters(true);

                TokenRestrictionTemplate tokenRestrictionTemplate = new TokenRestrictionTemplate(TokenType.JWT);

                var tokenVerificationKey   = new RsaTokenVerificationKey();
                tokenVerificationKey.InitFromRsaParameters(RSAParams);
                tokenRestrictionTemplate.PrimaryVerificationKey = tokenVerificationKey;

                tokenRestrictionTemplate.Audience = "http://sampleIssuerUrl";
                tokenRestrictionTemplate.Issuer = "http://sampleAudience";
                string requirements = TokenRestrictionTemplateSerializer.Serialize(tokenRestrictionTemplate);
            }
        }
        static private string GenerateTokenRequirements(TokenType mytokentype, string _sampleAudience, string _sampleIssuer, IList<TokenClaim> tokenclaimslist, bool AddContentKeyIdentifierClaim, TokenVerificationKey mytokenverificationkey, string openIdDiscoveryURL = null)
        {
            TokenRestrictionTemplate TokenrestrictionTemplate = new TokenRestrictionTemplate(mytokentype)
            {
                Audience = _sampleAudience,
                Issuer = _sampleIssuer,
            };

            if (AddContentKeyIdentifierClaim)
            {
                TokenrestrictionTemplate.RequiredClaims.Add(TokenClaim.ContentKeyIdentifierClaim);
            }

            if (openIdDiscoveryURL != null)
            {
                TokenrestrictionTemplate.OpenIdConnectDiscoveryDocument = new OpenIdConnectDiscoveryDocument(openIdDiscoveryURL);
            }
            else
            {
                TokenrestrictionTemplate.PrimaryVerificationKey = mytokenverificationkey;
            }

            foreach (var t in tokenclaimslist)
            {
                TokenrestrictionTemplate.RequiredClaims.Add(t);
            }
            return TokenRestrictionTemplateSerializer.Serialize(TokenrestrictionTemplate);
        }
        private void FetchKeyWithJWTAuth(string audience, string issuer)
        {
            IContentKey contentKey = null;
            IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = null;
            IContentKeyAuthorizationPolicyOption policyOption = null;

            try
            {
                byte[] expectedKey = null;
                contentKey = CreateTestKey(_mediaContext, ContentKeyType.EnvelopeEncryption, out expectedKey);

                var templatex509Certificate2 = new X509Certificate2("amscer.pfx", "AMSGIT");
                SigningCredentials cred = new X509SigningCredentials(templatex509Certificate2);

                TokenRestrictionTemplate tokenRestrictionTemplate = new TokenRestrictionTemplate(TokenType.JWT);
                tokenRestrictionTemplate.PrimaryVerificationKey = new X509CertTokenVerificationKey(templatex509Certificate2);
                tokenRestrictionTemplate.Audience = audience;
                tokenRestrictionTemplate.Issuer = issuer;

                string optionName = "GetHlsKeyDeliveryUrlAndFetchKeyWithJWTAuthentication";
                string requirements = TokenRestrictionTemplateSerializer.Serialize(tokenRestrictionTemplate);
                policyOption = ContentKeyAuthorizationPolicyOptionTests.CreateOption(_mediaContext, optionName,
                    ContentKeyDeliveryType.BaselineHttp, requirements, null, ContentKeyRestrictionType.TokenRestricted);

                JwtSecurityToken token = new JwtSecurityToken(issuer: tokenRestrictionTemplate.Issuer,
                    audience: tokenRestrictionTemplate.Audience, notBefore: DateTime.Now.AddMinutes(-5),
                    expires: DateTime.Now.AddMinutes(5), signingCredentials: cred);

                JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
                string jwtTokenString = handler.WriteToken(token);

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

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

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

                Assert.IsNotNull(keyDeliveryServiceUri);

                // Enable once all accounts are enabled for per customer Key Delivery Urls
                //Assert.IsTrue(keyDeliveryServiceUri.Host.StartsWith(_mediaContext.Credentials.ClientId));

                KeyDeliveryServiceClient keyClient = new KeyDeliveryServiceClient(RetryPolicy.DefaultFixed);
                byte[] key = keyClient.AcquireHlsKeyWithBearerHeader(keyDeliveryServiceUri, jwtTokenString);

                string expectedString = GetString(expectedKey);
                string fetchedString = GetString(key);
                Assert.AreEqual(expectedString, fetchedString);
            }
            finally
            {
                CleanupKeyAndPolicy(contentKey, contentKeyAuthorizationPolicy, policyOption);
            }
        }
        /// <summary>
        /// Serializes a TokenRestrictionTemplate to a string containing an xml representation of
        /// the token restriction template.
        /// </summary>
        /// <param name="template">TokenRestrictionTemplate instance to serialize to a string</param>
        /// <returns>An xml string representation of the TokenRestrictionTemplate instance</returns>
        public static string Serialize(TokenRestrictionTemplate template)
        {
            DataContractSerializer serializer = GetSerializer();

            return MediaServicesLicenseTemplateSerializer.SerializeToXml(template, serializer);
        }
        public void SetupTest()
        {
            _mediaContext = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext();

            PlayReadyLicenseResponseTemplate responseTemplate = new PlayReadyLicenseResponseTemplate();
            responseTemplate.LicenseTemplates.Add(new PlayReadyLicenseTemplate());

            TokenRestrictionTemplate tokenRestrictionTemplate = new TokenRestrictionTemplate(TokenType.JWT);
            tokenRestrictionTemplate.PrimaryVerificationKey = new SymmetricVerificationKey(); // the default constructor automatically generates a random key
            tokenRestrictionTemplate.Audience = "http://sampleIssuerUrl";
            tokenRestrictionTemplate.Issuer = "http://sampleAudience";

            string optionName = "integrationtest-crud-749";
            string requirements = TokenRestrictionTemplateSerializer.Serialize(tokenRestrictionTemplate);
            string configuration = MediaServicesLicenseTemplateSerializer.Serialize(responseTemplate);
            ContentKeyRestrictionType restrictionType = ContentKeyRestrictionType.TokenRestricted;

            _testOption = CreateOption(_mediaContext, optionName, ContentKeyDeliveryType.PlayReadyLicense, requirements, configuration, restrictionType);
        }
        /// <summary>
        /// This function sets up a ContentKeyAuthorizationPolicyRestriction from the given inputs.  This enables the
        /// Key Delivery Service to validate tokens presented by clients against this values, ensuring that the tokens
        /// are signed with the correct key and that they have the specified issuer and scope value.
        /// </summary>
        /// <param name="name">The name given to the ContentKeyAuthorizationPolicyRestriction object</param>
        /// <param name="issuer">The ACS endpoint to send the token request to</param>
        /// <param name="scope">The Realm configured in the ACS Relying Party Application</param>
        /// <param name="signingKey">The TokenSigning Keyfrom the ACS Relying Party Application</param>
        /// <returns>A list containing a single policy restriction requiring the client to provide a token with the given parameters</returns>
        private static List<ContentKeyAuthorizationPolicyRestriction> GetTokenRestriction(string name, string issuer, string scope, byte[] signingKey)
        {
            TokenRestrictionTemplate tokenTemplate = new TokenRestrictionTemplate();
            tokenTemplate.Issuer = issuer;
            tokenTemplate.Audience = scope;
            tokenTemplate.TokenType = TokenType.SWT;
            tokenTemplate.PrimaryVerificationKey = new SymmetricVerificationKey(signingKey);

            string requirements = TokenRestrictionTemplateSerializer.Serialize(tokenTemplate);

            List<ContentKeyAuthorizationPolicyRestriction> restrictions = new List<ContentKeyAuthorizationPolicyRestriction>()
                {
                    new ContentKeyAuthorizationPolicyRestriction()
                        {
                            KeyRestrictionType = (int)ContentKeyRestrictionType.TokenRestricted,
                            Requirements = requirements,
                            Name = name
                        }
                };

            return restrictions;
        }