Ejemplo n.º 1
0
        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));
        }
        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));
        }
        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);
            }
        }
        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);
            }
        }
Ejemplo n.º 5
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 RSATokenVerificationKeySerializeShouldIncudePrpoperTypeAttribbute()
        {
            TokenRestrictionTemplate template             = new TokenRestrictionTemplate(TokenType.JWT);
            RsaTokenVerificationKey  tokenVerificationKey = new RsaTokenVerificationKey();

            template.PrimaryVerificationKey = tokenVerificationKey;
            var templateAsString = TokenRestrictionTemplateSerializer.Serialize(template);

            Assert.IsTrue(templateAsString.Contains("<PrimaryVerificationKey i:type=\"RsaTokenVerificationKey\">"));
        }
Ejemplo n.º 7
0
        static private string GenerateTokenRequirements(Uri _sampleAudience, Uri _sampleIssuer)
        {
            TokenRestrictionTemplate template = new TokenRestrictionTemplate();

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

            return(TokenRestrictionTemplateSerializer.Serialize(template));
        }
Ejemplo n.º 8
0
        static private string GenerateTokenRequirements()
        {
            TokenRestrictionTemplate template = new TokenRestrictionTemplate(TokenType.SWT);

            template.PrimaryVerificationKey = new SymmetricVerificationKey();
            template.AlternateVerificationKeys.Add(new SymmetricVerificationKey());
            template.Audience = ConfigurationManager.AppSettings["Audience"];
            template.Issuer   = ConfigurationManager.AppSettings["Issuer"];

            template.RequiredClaims.Add(TokenClaim.ContentKeyIdentifierClaim);

            return(TokenRestrictionTemplateSerializer.Serialize(template));
        }
        private List <ContentKeyAuthorizationPolicyRestriction> CreateContentKeyAuthPolicyRestrictions(string policyName, ContentProtection contentProtection)
        {
            List <ContentKeyAuthorizationPolicyRestriction> policyRestrictions = new List <ContentKeyAuthorizationPolicyRestriction>();

            if (contentProtection.ContentAuthTypeAddress)
            {
                ContentKeyAuthorizationPolicyRestriction policyRestriction = new ContentKeyAuthorizationPolicyRestriction();
                policyRestriction.Name = string.Concat(policyName, Constant.Media.ContentProtection.AuthPolicyAddressRestrictionName);
                policyRestriction.SetKeyRestrictionTypeValue(ContentKeyRestrictionType.IPRestricted);
                policyRestriction.Requirements = GetAddressRangeXml(contentProtection.ContentAuthAddressRange);
                policyRestrictions.Add(policyRestriction);
            }
            if (contentProtection.ContentAuthTypeToken)
            {
                string settingKey = Constant.AppSettingKey.DirectoryTenantId;
                settingKey = string.Format(settingKey, contentProtection.DirectoryId);
                string directoryTenantId = AppSetting.GetValue(settingKey);

                settingKey = Constant.AppSettingKey.DirectoryTenantDomain;
                settingKey = string.Format(settingKey, contentProtection.DirectoryId);
                string directoryTenantDomain = AppSetting.GetValue(settingKey);

                string discoveryUrl = Account.GetDiscoveryUrl(contentProtection.DirectoryId, directoryTenantDomain);
                if (string.Equals(contentProtection.DirectoryId, Constant.DirectoryService.B2C, StringComparison.OrdinalIgnoreCase))
                {
                    settingKey = Constant.AppSettingKey.DirectoryPolicyIdSignUpIn;
                    string policyIdSignUpIn = AppSetting.GetValue(settingKey);
                    discoveryUrl = string.Concat(discoveryUrl, "?p=", policyIdSignUpIn);
                }

                TokenRestrictionTemplate tokenTemplate = new TokenRestrictionTemplate(TokenType.JWT);
                tokenTemplate.OpenIdConnectDiscoveryDocument = new OpenIdConnectDiscoveryDocument(discoveryUrl);
                tokenTemplate.Issuer   = Account.GetIssuerUrl(contentProtection.DirectoryId, directoryTenantId);
                tokenTemplate.Audience = contentProtection.Audience;

                ContentKeyAuthorizationPolicyRestriction policyRestriction = new ContentKeyAuthorizationPolicyRestriction();
                policyRestriction.Name = string.Concat(policyName, Constant.Media.ContentProtection.AuthPolicyTokenRestrictionName);
                policyRestriction.SetKeyRestrictionTypeValue(ContentKeyRestrictionType.TokenRestricted);
                policyRestriction.Requirements = TokenRestrictionTemplateSerializer.Serialize(tokenTemplate);
                policyRestrictions.Add(policyRestriction);
            }
            if (policyRestrictions.Count == 0)
            {
                ContentKeyAuthorizationPolicyRestriction policyRestriction = new ContentKeyAuthorizationPolicyRestriction();
                policyRestriction.Name = string.Concat(policyName, Constant.Media.ContentProtection.AuthPolicyOpenRestrictionName);
                policyRestriction.SetKeyRestrictionTypeValue(ContentKeyRestrictionType.Open);
                policyRestrictions.Add(policyRestriction);
            }
            return(policyRestrictions);
        }
Ejemplo n.º 10
0
        private static string GetJwtRequirements()
        {
            var primaryVerificationKey = ConfigurationManager.AppSettings["JWTRestrictionPrimaryVerificationKeyBase64"];
            var audience = ConfigurationManager.AppSettings["JWTRestrictionAudience"];
            var issuer   = ConfigurationManager.AppSettings["JWTRestrictionIssuer"];

            var template = new TokenRestrictionTemplate(TokenType.JWT)
            {
                PrimaryVerificationKey = new SymmetricVerificationKey(Convert.FromBase64String(primaryVerificationKey)),
                Audience = audience,
                Issuer   = issuer
            };

            return(TokenRestrictionTemplateSerializer.Serialize(template));
        }
        public void TokenRestrictionTemplateSerializeNotPrimaryKeyAndNoOpenConnectIdDocument()
        {
            TokenRestrictionTemplate template = new TokenRestrictionTemplate(TokenType.JWT);

            template.Audience = _sampleAudience;
            template.Issuer   = _sampleIssuer;
            try
            {
                TokenRestrictionTemplateSerializer.Serialize(template);
            }
            catch (Exception ex)
            {
                Assert.AreEqual("Both PrimaryVerificationKey and OpenIdConnectDiscoveryDocument are null", ex.Message);
                throw;
            }
        }
Ejemplo n.º 12
0
        /*This code generates the following XML:
         * <TokenRestrictionTemplate xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/Azure/MediaServices/KeyDelivery/TokenRestrictionTemplate/v1">
         * <AlternateVerificationKeys>
         *  <TokenVerificationKey i:type="SymmetricVerificationKey">
         *    <KeyValue>hhv74VzJ+pOiuYw1z2wxh6ZkX4tRl/WVhBTvM6T/vUo=</KeyValue>
         *  </TokenVerificationKey>
         * </AlternateVerificationKeys>
         * <Audience>urn:test</Audience>
         * <Issuer>https://willzhanacs.accesscontrol.windows.net/</Issuer>
         * <PrimaryVerificationKey i:type="SymmetricVerificationKey">
         *  <KeyValue>7V1WtGGAylmZTMKA8RlVMrPNhukYBF2sW04UMpuD8bw=</KeyValue>
         * </PrimaryVerificationKey>
         * <RequiredClaims>
         *  <TokenClaim>
         *    <ClaimType>urn:microsoft:azure:mediaservices:contentkeyidentifier</ClaimType>
         *    <ClaimValue i:nil="true" />
         *  </TokenClaim>
         * </RequiredClaims>
         * </TokenRestrictionTemplate>
         *
         * <TokenRestrictionTemplate xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/Azure/MediaServices/KeyDelivery/TokenRestrictionTemplate/v1">
         * <AlternateVerificationKeys>
         *  <TokenVerificationKey i:type="SymmetricVerificationKey">
         *    <KeyValue>hhv74VzJ+pOiuYw1z2wxh6ZkX4tRl/WVhBTvM6T/vUo=</KeyValue>
         *  </TokenVerificationKey>
         * </AlternateVerificationKeys>
         * <Audience>urn:test</Audience>
         * <Issuer>https://willzhanacs.accesscontrol.windows.net/</Issuer>
         * <PrimaryVerificationKey i:type="SymmetricVerificationKey">
         *  <KeyValue>7V1WtGGAylmZTMKA8RlVMrPNhukYBF2sW04UMpuD8bw=</KeyValue>
         * </PrimaryVerificationKey>
         * <RequiredClaims />
         * </TokenRestrictionTemplate>
         */
        //Sample code: https://raw.githubusercontent.com/Azure/azure-media-services-samples/master/KDWithACS/ConsoleApplication6/Program.cs
        public static string CreateRestrictionRequirements()
        {
            string primarySymmetricKey   = System.Configuration.ConfigurationManager.AppSettings["PrimarySymmetricKey"];
            string secondarySymmetricKey = System.Configuration.ConfigurationManager.AppSettings["SecondarySymmetricKey"];
            string scope  = System.Configuration.ConfigurationManager.AppSettings["AcsScope"];
            string issuer = System.Configuration.ConfigurationManager.AppSettings["AcsIssuer"];

            TokenRestrictionTemplate objTokenRestrictionTemplate = new TokenRestrictionTemplate();

            objTokenRestrictionTemplate.PrimaryVerificationKey = new SymmetricVerificationKey(Convert.FromBase64String(primarySymmetricKey));
            objTokenRestrictionTemplate.AlternateVerificationKeys.Add(new SymmetricVerificationKey(Convert.FromBase64String(secondarySymmetricKey)));
            objTokenRestrictionTemplate.Audience = new Uri(scope);
            objTokenRestrictionTemplate.Issuer   = new Uri(issuer);
            //objTokenRestrictionTemplate.RequiredClaims.Add(TokenClaim.ContentKeyIdentifierClaim);
            objTokenRestrictionTemplate.TokenType = TokenType.SWT;                //new change: the default is JWT, a "gotcha"

            return(TokenRestrictionTemplateSerializer.Serialize(objTokenRestrictionTemplate));
        }
        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));
        }
Ejemplo n.º 14
0
        private List <ContentKeyAuthorizationPolicyRestriction> CreateContentKeyAuthPolicyRestrictions(string policyName, ContentProtection contentProtection)
        {
            List <ContentKeyAuthorizationPolicyRestriction> policyRestrictions = new List <ContentKeyAuthorizationPolicyRestriction>();

            if (contentProtection.ContentAuthTypeAddress)
            {
                ContentKeyAuthorizationPolicyRestriction policyRestriction = new ContentKeyAuthorizationPolicyRestriction();
                policyRestriction.Name = string.Concat(policyName, Constants.Media.ContentProtection.AuthPolicyAddressRestrictionName);
                policyRestriction.SetKeyRestrictionTypeValue(ContentKeyRestrictionType.IPRestricted);
                policyRestriction.Requirements = GetAddressRangeXml(contentProtection.ContentAuthAddressRange);
                policyRestrictions.Add(policyRestriction);
            }
            if (contentProtection.ContentAuthTypeToken)
            {
                string settingKey   = Constants.AppSettingKey.DirectoryDiscoveryUrl;
                string discoveryUrl = AppSetting.GetValue(settingKey);

                settingKey = Constants.AppSettingKey.DirectoryIssuerUrl;
                string issuerUrl = AppSetting.GetValue(settingKey);

                settingKey = Constants.AppSettingKey.DirectoryClientId;
                string clientId = AppSetting.GetValue(settingKey);

                TokenRestrictionTemplate tokenTemplate = new TokenRestrictionTemplate(TokenType.JWT);
                tokenTemplate.OpenIdConnectDiscoveryDocument = new OpenIdConnectDiscoveryDocument(discoveryUrl);
                tokenTemplate.Issuer   = issuerUrl;
                tokenTemplate.Audience = clientId;

                ContentKeyAuthorizationPolicyRestriction policyRestriction = new ContentKeyAuthorizationPolicyRestriction();
                policyRestriction.Name = string.Concat(policyName, Constants.Media.ContentProtection.AuthPolicyTokenRestrictionName);
                policyRestriction.SetKeyRestrictionTypeValue(ContentKeyRestrictionType.TokenRestricted);
                policyRestriction.Requirements = TokenRestrictionTemplateSerializer.Serialize(tokenTemplate);
                policyRestrictions.Add(policyRestriction);
            }
            if (policyRestrictions.Count == 0)
            {
                ContentKeyAuthorizationPolicyRestriction policyRestriction = new ContentKeyAuthorizationPolicyRestriction();
                policyRestriction.Name = string.Concat(policyName, Constants.Media.ContentProtection.AuthPolicyOpenRestrictionName);
                policyRestriction.SetKeyRestrictionTypeValue(ContentKeyRestrictionType.Open);
                policyRestrictions.Add(policyRestriction);
            }
            return(policyRestrictions);
        }
        public void RSATokenVerificationKeyRoundTrip()
        {
            TokenRestrictionTemplate template             = new TokenRestrictionTemplate(TokenType.JWT);
            RsaTokenVerificationKey  tokenVerificationKey = new RsaTokenVerificationKey();
            RSAParameters            inputRsaParameters;

            using (RSACryptoServiceProvider provider = new RSACryptoServiceProvider())
            {
                inputRsaParameters = provider.ExportParameters(true);

                tokenVerificationKey.InitFromRsaParameters(inputRsaParameters);
            }
            Assert.IsNotNull(tokenVerificationKey.RawBody);
            template.Audience = _sampleAudience;
            template.Issuer   = _sampleIssuer;
            template.PrimaryVerificationKey = tokenVerificationKey;
            var templateAsString = TokenRestrictionTemplateSerializer.Serialize(template);

            Assert.IsTrue(templateAsString.Contains("<PrimaryVerificationKey i:type=\"RsaTokenVerificationKey\">"));
            TokenRestrictionTemplate output = TokenRestrictionTemplateSerializer.Deserialize(templateAsString);

            Assert.AreEqual(TokenType.JWT, output.TokenType);
            Assert.IsNotNull(output.PrimaryVerificationKey);
            Assert.IsNotNull(output.PrimaryVerificationKey as RsaTokenVerificationKey);
            RsaTokenVerificationKey key = output.PrimaryVerificationKey as RsaTokenVerificationKey;

            Assert.IsNotNull(key.RawBody);
            RSAParameters outputRsaParametersutParameters = key.GetRsaParameters();

            Assert.IsNotNull(outputRsaParametersutParameters);
            Assert.IsNotNull(outputRsaParametersutParameters.Exponent);
            Assert.IsNotNull(outputRsaParametersutParameters.Modulus);
            //Check that we are storing only public signing key
            Assert.IsNull(outputRsaParametersutParameters.P);
            Assert.IsNull(outputRsaParametersutParameters.Q);
            Assert.IsNull(outputRsaParametersutParameters.D);
            Assert.IsNull(outputRsaParametersutParameters.DP);
            Assert.IsNull(outputRsaParametersutParameters.DQ);
            //Checking that public key matching
            Assert.IsTrue(inputRsaParameters.Exponent.SequenceEqual(outputRsaParametersutParameters.Exponent), "Exponent value mismatch");
            Assert.IsTrue(inputRsaParameters.Modulus.SequenceEqual(outputRsaParametersutParameters.Modulus), "Modulus value mismatch");
        }
        private static string GenerateTokenRequirements()
        {
            TokenType tType = TokenType.SWT;

            if (_isTokenTypeJWT)
            {
                tType = TokenType.JWT;
            }
            TokenRestrictionTemplate template = new TokenRestrictionTemplate(tType);

            template.PrimaryVerificationKey = new SymmetricVerificationKey(Convert.FromBase64String(_symmetricVerificationKey));
            //template.AlternateVerificationKeys.Add(new SymmetricVerificationKey());
            template.Audience = _sampleAudience.ToString();
            template.Issuer   = _sampleIssuer.ToString();
            if (_enableKidClaim)
            {
                template.RequiredClaims.Add(TokenClaim.ContentKeyIdentifierClaim);
            }
            return(TokenRestrictionTemplateSerializer.Serialize(template));
        }
Ejemplo n.º 17
0
        private static void CreatePolicyOption(string assetID, CloudMediaContext mediaContext, string claimType, string claim, IContentKeyAuthorizationPolicy policy)
        {
            IContentKeyAuthorizationPolicyOption            policyOption;
            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(claim))
            {
                template.RequiredClaims.Add(new TokenClaim(claimType, claim));
            }

            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 + "_group:" + claim, ContentKeyDeliveryType.BaselineHttp, restrictions, null);
            policy.Options.Add(policyOption);
        }
Ejemplo n.º 18
0
        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);
        }
        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);
            }
        }
Ejemplo n.º 20
0
        //for JWT token issued by AAD
        public static string CreateRestrictionRequirementsForJWT()
        {
            string audience = System.Configuration.ConfigurationManager.AppSettings["ida:audience"];
            string issuer   = System.Configuration.ConfigurationManager.AppSettings["ida:issuer"];

            List <X509Certificate2> objList_cert = GetX509Certificate2FromADMetadataEndpoint();

            TokenRestrictionTemplate objTokenRestrictionTemplate = new TokenRestrictionTemplate();

            objTokenRestrictionTemplate.PrimaryVerificationKey = new X509CertTokenVerificationKey(objList_cert[0]);
            objList_cert.GetRange(1, objList_cert.Count - 1).ForEach(c => objTokenRestrictionTemplate.AlternateVerificationKeys.Add(new X509CertTokenVerificationKey(c)));
            objTokenRestrictionTemplate.Audience  = new Uri(audience);
            objTokenRestrictionTemplate.Issuer    = new Uri(issuer);
            objTokenRestrictionTemplate.TokenType = TokenType.JWT;

            //add required claims
            string entitledGroupObjectId = System.Configuration.ConfigurationManager.AppSettings["ida:EntitledGroupObjectId"];

            objTokenRestrictionTemplate.RequiredClaims.Add(new TokenClaim("groups", entitledGroupObjectId));

            return(TokenRestrictionTemplateSerializer.Serialize(objTokenRestrictionTemplate));
        }
Ejemplo n.º 21
0
        static private string GenerateTokenRequirements(byte[] tokenSecret, TokenType tokenType, string audience, string issuer, TokenClaim[] tokenClaims)
        {
            TokenRestrictionTemplate template = new TokenRestrictionTemplate(tokenType)
            {
                PrimaryVerificationKey = new SymmetricVerificationKey(tokenSecret),
                Audience = audience,
                Issuer   = issuer,
            };

            // template.AlternateVerificationKeys.Add(new SymmetricVerificationKey());
            // could add an alternate key here, but easy to just share secret with other sites since we use only one

            if (tokenClaims != null)
            {
                foreach (TokenClaim claim in tokenClaims)
                {
                    template.RequiredClaims.Add(claim);
                }
            }

            return(TokenRestrictionTemplateSerializer.Serialize(template));
        }
        public void OpenIdDocumentAsVerificationKeyRoundTrip()
        {
            string openConnectId   = "https://openconnectIddiscoveryUri";
            string expectedElement =
                "<OpenIdConnectDiscoveryDocument><OpenIdDiscoveryUri>https://openconnectIddiscoveryUri</OpenIdDiscoveryUri>";

            TokenRestrictionTemplate template = new TokenRestrictionTemplate(TokenType.JWT);

            template.Audience = _sampleAudience;
            template.Issuer   = _sampleIssuer;
            template.OpenIdConnectDiscoveryDocument = new OpenIdConnectDiscoveryDocument(openConnectId);
            var templateAsString = TokenRestrictionTemplateSerializer.Serialize(template);

            Assert.IsTrue(templateAsString.Contains("<PrimaryVerificationKey i:nil=\"true\" />"));
            Assert.IsTrue(templateAsString.Contains(expectedElement));
            TokenRestrictionTemplate output = TokenRestrictionTemplateSerializer.Deserialize(templateAsString);

            Assert.IsNotNull(output);
            Assert.IsNotNull(output.OpenIdConnectDiscoveryDocument);
            Assert.IsNull(output.PrimaryVerificationKey);
            Assert.AreEqual(0, output.AlternateVerificationKeys.Count);
            Assert.AreEqual(output.OpenIdConnectDiscoveryDocument.OpenIdDiscoveryUri, openConnectId);
        }
Ejemplo n.º 23
0
        /// <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);
        }
        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);
        }
        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.AcquireTokenAsync(appResourceId, clientCredential).Result;
                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);
            }
        }
Ejemplo n.º 26
0
        public static string GenerateTokenRequirementsString(string primaryVerificationKey, string alternativeVerificationKey, string scope, string issuer, bool requireContentKeyIdentifier, params TokenClaim[] claims)
        {
            var tokenTemplate = GenerateTokenRequirements(primaryVerificationKey, alternativeVerificationKey, scope, issuer, requireContentKeyIdentifier, claims);

            return(TokenRestrictionTemplateSerializer.Serialize(tokenTemplate));
        }