public void InputMissingPrimaryKeyShouldThrow()
        {
            string tokenTemplate = "<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>GG07fDPZ+HMD2vcoknMqYjEJMb7LSq8zUmdCYMvRCevnQK//ilbhODO/FydMrHiwZGmI6XywvOOU7SSzRPlI3Q==</KeyValue></TokenVerificationKey></AlternateVerificationKeys><Audience>http://sampleaudience/</Audience><Issuer>http://sampleissuerurl/</Issuer><RequiredClaims><TokenClaim><ClaimType>urn:microsoft:azure:mediaservices:contentkeyidentifier</ClaimType><ClaimValue i:nil=\"true\" /></TokenClaim><TokenClaim><ClaimType>urn:myservice:claims:rental</ClaimType><ClaimValue>true</ClaimValue></TokenClaim></RequiredClaims></TokenRestrictionTemplate>";

            try
            {
                TokenRestrictionTemplate template = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplate);
                Assert.Fail("Should throw");
            }
            catch (InvalidDataContractException e)
            {
                Assert.IsTrue(e.Message.Contains("Both PrimaryVerificationKey and OpenIdConnectDiscoveryDocument are null"));
                throw;
            }
        }
Beispiel #2
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));
        }
Beispiel #3
0
        private void listViewAutOptions_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool NoVerifKey = false;

            if (listViewAutOptions.SelectedIndices.Count > 0)
            {
                var    it             = listViewAutOptions.SelectedItems[0];
                string stringoptionid = it.SubItems[2].Text;
                SelectedOption = mycontext.ContentKeyAuthorizationPolicyOptions.Where(p => p.Id == stringoptionid).FirstOrDefault();

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

                string tokenTemplateString = SelectedOption.Restrictions.FirstOrDefault().Requirements;
                if (!string.IsNullOrEmpty(tokenTemplateString))
                {
                    TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString);
                    textBoxAudience.Text = tokenTemplate.Audience.ToString();
                    textBoxIssuer.Text   = tokenTemplate.Issuer.ToString();
                    checkBoxAddContentKeyIdentifierClaim.Checked = false;
                    groupBoxStartDate.Enabled = (tokenTemplate.TokenType == TokenType.JWT);
                    if (tokenTemplate.PrimaryVerificationKey != null)
                    {
                        panelJWTX509Cert.Enabled = !(tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey));
                    }
                    else
                    {
                        NoVerifKey = true; // Case for OpenId for example. No way to create a test token....
                    }
                    TokenClaimsList.Clear();
                    foreach (var claim in tokenTemplate.RequiredClaims)
                    {
                        if (claim.ClaimType == TokenClaim.ContentKeyIdentifierClaimType)
                        {
                            checkBoxAddContentKeyIdentifierClaim.Checked = true;
                        }
                        else
                        {
                            TokenClaimsList.Add(new MyTokenClaim()
                            {
                                Type  = claim.ClaimType,
                                Value = claim.ClaimValue
                            });
                        }
                    }
                }
                UpdateButtonOk(NoVerifKey);
            }
        }
        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;
            }
        }
Beispiel #5
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));
        }
Beispiel #6
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);
        }
        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));
        }
        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));
        }
Beispiel #10
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);
        }
Beispiel #11
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);
            }
        }
Beispiel #13
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));
        }
Beispiel #14
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));
        }
Beispiel #15
0
        public static string GetTestToken(string assetid, IAsset asset = null)
        {
            if (asset == null)
            {
                asset = GetAssetById(assetid);
            }

            IContentKey key = asset.ContentKeys.FirstOrDefault();

            if (key != null && key.AuthorizationPolicyId != null)
            {
                IContentKeyAuthorizationPolicy policy = context.ContentKeyAuthorizationPolicies.Where(p => p.Id == key.AuthorizationPolicyId).FirstOrDefault();

                if (policy != null)
                {
                    IContentKeyAuthorizationPolicyOption option = null;
                    option = policy.Options.Where(o => (ContentKeyRestrictionType)o.Restrictions.FirstOrDefault().KeyRestrictionType == ContentKeyRestrictionType.TokenRestricted).FirstOrDefault();

                    if (option != null)
                    {
                        string tokenTemplateString = option.Restrictions.FirstOrDefault().Requirements;

                        if (!string.IsNullOrEmpty(tokenTemplateString))
                        {
                            Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(key.Id);
                            TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString);

                            if (tokenTemplate.TokenType == TokenType.SWT) //SWT
                            {
                                return("Bearer " + TokenRestrictionTemplateSerializer.GenerateTestToken(tokenTemplate, null, rawkey, DateTime.UtcNow.AddDays(1)));
                            }
                        }
                    }
                }
            }

            return(null);
        }
Beispiel #16
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 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);
        }
        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);
        }
Beispiel #19
0
        public static TokenRestrictionTemplate GenerateTokenRequirements(string primaryVerificationKey, string alternativeVerificationKey, string scope, string issuer, bool requireContentKeyIdentifier, params TokenClaim[] claims)
        {
            TokenRestrictionTemplate template = new TokenRestrictionTemplate(TokenType.SWT);

            template.PrimaryVerificationKey = new SymmetricVerificationKey(Convert.FromBase64String(primaryVerificationKey));
            template.AlternateVerificationKeys.Add(new SymmetricVerificationKey(Convert.FromBase64String(alternativeVerificationKey)));
            template.Audience = scope;
            template.Issuer   = issuer;

            // This claim requires that the value of the claim in the token must match the key identifier of the key being requested by the client.
            // Adding this claim means that the token issued to the client authorizes access to the content key identifier listed in the token.
            if (requireContentKeyIdentifier)
            {
                template.RequiredClaims.Add(TokenClaim.ContentKeyIdentifierClaim);
            }

            // Add any other claims
            foreach (var claim in claims)
            {
                template.RequiredClaims.Add(claim);
            }

            return(template);
        }
Beispiel #20
0
        public CreateTestToken(IAsset _asset, CloudMediaContext _context, ContentKeyType?keytype = null, string optionid = null)
        {
            InitializeComponent();
            this.Icon = Bitmaps.Azure_Explorer_ico;

            MyAsset   = _asset;
            mycontext = _context;

            var query = from key in MyAsset.ContentKeys
                        join autpol in _context.ContentKeyAuthorizationPolicies on key.AuthorizationPolicyId equals autpol.Id
                        select new { keyname = key.Name, keytype = key.ContentKeyType, keyid = key.Id, aupolid = autpol.Id };


            listViewAutOptions.BeginUpdate();
            listViewAutOptions.Items.Clear();
            foreach (var key in query)
            {
                var queryoptions = _context.ContentKeyAuthorizationPolicies.Where(a => a.Id == key.aupolid).FirstOrDefault().Options;

                foreach (var option in queryoptions)
                {
                    if (option.Restrictions.FirstOrDefault().KeyRestrictionType == (int)ContentKeyRestrictionType.TokenRestricted)
                    {
                        ListViewItem item = new ListViewItem(key.keytype.ToString());

                        IContentKey keyj = MyAsset.ContentKeys.Where(k => k.Id == key.keyid).FirstOrDefault();
                        ContentKeyDisplayed.Add(keyj);

                        item.SubItems.Add(option.Name);
                        item.SubItems.Add(option.Id);
                        string tokenTemplateString = option.Restrictions.FirstOrDefault().Requirements;
                        if (!string.IsNullOrEmpty(tokenTemplateString))
                        {
                            TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString);

                            item.SubItems.Add(tokenTemplate.TokenType == TokenType.JWT ? "JWT" : "SWT");
                            if (tokenTemplate.PrimaryVerificationKey != null)
                            {
                                item.SubItems.Add(tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey) ? "Symmetric" : "Asymmetric X509");
                            }
                            else if (tokenTemplate.OpenIdConnectDiscoveryDocument != null)
                            {
                                item.SubItems.Add("OpenID");
                            }
                        }
                        listViewAutOptions.Items.Add(item);
                        if (optionid == option.Id)
                        {
                            listViewAutOptions.Items[listViewAutOptions.Items.IndexOf(item)].Selected = true;
                        }
                    }
                }
            }

            if (listViewAutOptions.Items.Count > 0 && listViewAutOptions.SelectedItems.Count == 0) // no selection, in that case, first line selected
            {
                listViewAutOptions.Items[0].Selected = true;
            }

            listViewAutOptions.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            listViewAutOptions.EndUpdate();
        }
Beispiel #21
0
        static void Main(string[] args)
        {
            // Create and cache the Media Services credentials in a static class variable.
            _cachedCredentials = new MediaServicesCredentials(
                _mediaServicesAccountName,
                _mediaServicesAccountKey);
            // Used the chached credentials to create CloudMediaContext.
            _context = new CloudMediaContext(_cachedCredentials);

            bool   tokenRestriction    = true;
            string tokenTemplateString = null;

            IAsset asset = UploadFileAndCreateAsset(_singleMP4File);

            Console.WriteLine("Uploaded asset: {0}", asset.Id);

            IAsset encodedAsset = EncodeToAdaptiveBitrateMP4Set(asset);

            Console.WriteLine("Encoded asset: {0}", encodedAsset.Id);

            IContentKey key = CreateEnvelopeTypeContentKey(encodedAsset);

            Console.WriteLine("Created key {0} for the asset {1} ", key.Id, encodedAsset.Id);
            Console.WriteLine();

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

            Console.WriteLine("Added authorization policy: {0}", key.AuthorizationPolicyId);
            Console.WriteLine();

            CreateAssetDeliveryPolicy(encodedAsset, key);
            Console.WriteLine("Created asset delivery policy. \n");
            Console.WriteLine();

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

                // Generate a test token based on the data in the given TokenRestrictionTemplate.
                // Note, you need to pass the key id Guid because we specified
                // TokenClaim.ContentKeyIdentifierClaim in during the creation of TokenRestrictionTemplate.
                Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(key.Id);

                //The GenerateTestToken method returns the token without the word “Bearer” in front
                //so you have to add it in front of the token string.
                string testToken = TokenRestrictionTemplateSerializer.GenerateTestToken(tokenTemplate, null, rawkey, DateTime.UtcNow.AddDays(365));

                Console.WriteLine("The authorization token is:\nBearer {0}", testToken);
                Console.WriteLine();
            }

            // You can use the bit.ly/aesplayer Flash player to test the URL
            // (with open authorization policy).
            // Paste the URL and click the Update button to play the video.
            //
            string URL = GetStreamingOriginLocator(encodedAsset);

            Console.WriteLine("Smooth Streaming Url: {0}/manifest", URL);
            Console.WriteLine();
            Console.WriteLine("HLS Url: {0}/manifest(format=m3u8-aapl)", URL);
            Console.WriteLine();

            Console.ReadLine();
        }
Beispiel #22
0
        public static TokenResult GetTestToken(IAsset MyAsset, CloudMediaContext _context, ContentKeyType?keytype = null, SigningCredentials signingcredentials = null, string optionid = null, bool displayUI = false)
        {
            TokenResult MyResult = new TokenResult();

            /// WITH UI
            if (displayUI)
            {
                CreateTestToken form = new CreateTestToken(MyAsset, _context, keytype, optionid)
                {
                    StartDate = DateTime.Now.AddMinutes(-5), EndDate = DateTime.Now.AddMinutes(Properties.Settings.Default.DefaultTokenDuration)
                };
                if (form.ShowDialog() == DialogResult.OK)
                {
                    if (form.GetOption != null)
                    {
                        string tokenTemplateString = form.GetOption.Restrictions.FirstOrDefault().Requirements;
                        if (!string.IsNullOrEmpty(tokenTemplateString))
                        {
                            Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(form.GetContentKeyFromSelectedOption.Id);
                            TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString);

                            if (tokenTemplate.OpenIdConnectDiscoveryDocument == null)
                            {
                                MyResult.TokenType           = tokenTemplate.TokenType;
                                MyResult.IsTokenKeySymmetric = (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey));
                                MyResult.ContentKeyType      = form.GetContentKeyFromSelectedOption.ContentKeyType;

                                if (tokenTemplate.TokenType == TokenType.SWT) //SWT
                                {
                                    MyResult.TokenString = TokenRestrictionTemplateSerializer.GenerateTestToken(tokenTemplate, null, rawkey, form.EndDate);
                                }
                                else // JWT
                                {
                                    IList <Claim> myclaims = null;
                                    myclaims = form.GetTokenRequiredClaims;
                                    if (form.PutContentKeyIdentifier)
                                    {
                                        myclaims.Add(new Claim(TokenClaim.ContentKeyIdentifierClaimType, rawkey.ToString()));
                                    }

                                    if (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey))
                                    {
                                        InMemorySymmetricSecurityKey tokenSigningKey = new InMemorySymmetricSecurityKey((tokenTemplate.PrimaryVerificationKey as SymmetricVerificationKey).KeyValue);
                                        signingcredentials = new SigningCredentials(tokenSigningKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);
                                    }
                                    else if (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(X509CertTokenVerificationKey))
                                    {
                                        X509Certificate2 cert = form.GetX509Certificate;
                                        if (cert != null)
                                        {
                                            signingcredentials = new X509SigningCredentials(cert);
                                        }
                                    }
                                    JwtSecurityToken        token   = new JwtSecurityToken(issuer: form.GetIssuerUri, audience: form.GetAudienceUri, notBefore: form.StartDate, expires: form.EndDate, signingCredentials: signingcredentials, claims: myclaims);
                                    JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
                                    MyResult.TokenString = handler.WriteToken(token);
                                }
                            }
                        }
                    }
                }
            }
            /////////////////////////////// NO UI
            else if (keytype != null)
            {
                IContentKey key = MyAsset.ContentKeys.Where(k => k.ContentKeyType == keytype).FirstOrDefault();
                if (key != null && key.AuthorizationPolicyId != null)
                {
                    IContentKeyAuthorizationPolicy policy = _context.ContentKeyAuthorizationPolicies.Where(p => p.Id == key.AuthorizationPolicyId).FirstOrDefault();
                    if (policy != null)
                    {
                        IContentKeyAuthorizationPolicyOption option = null;
                        if (optionid == null) // user does not want a specific option
                        {
                            option = policy.Options.Where(o => (ContentKeyRestrictionType)o.Restrictions.FirstOrDefault().KeyRestrictionType == ContentKeyRestrictionType.TokenRestricted).FirstOrDefault();
                        }
                        else
                        {
                            option = policy.Options.Where(o => o.Id == optionid).FirstOrDefault(); // user wants a token for a specific option
                        }

                        if (option != null) // && option.Restrictions.FirstOrDefault() != null && option.Restrictions.FirstOrDefault().KeyRestrictionType == (int)ContentKeyRestrictionType.TokenRestricted)
                        {
                            string tokenTemplateString = option.Restrictions.FirstOrDefault().Requirements;
                            if (!string.IsNullOrEmpty(tokenTemplateString))
                            {
                                Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(key.Id);
                                TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString);

                                if (tokenTemplate.OpenIdConnectDiscoveryDocument == null)
                                {
                                    MyResult.TokenType           = tokenTemplate.TokenType;
                                    MyResult.IsTokenKeySymmetric = (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey));
                                    MyResult.ContentKeyType      = (ContentKeyType)keytype;

                                    if (tokenTemplate.TokenType == TokenType.SWT) //SWT
                                    {
                                        MyResult.TokenString = TokenRestrictionTemplateSerializer.GenerateTestToken(tokenTemplate, null, rawkey, DateTime.Now.AddMinutes(Properties.Settings.Default.DefaultTokenDuration));
                                    }
                                    else // JWT
                                    {
                                        List <Claim> myclaims = null;
                                        myclaims = new List <Claim>();
                                        myclaims.Add(new Claim(TokenClaim.ContentKeyIdentifierClaimType, rawkey.ToString()));

                                        if (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey))
                                        {
                                            InMemorySymmetricSecurityKey tokenSigningKey = new InMemorySymmetricSecurityKey((tokenTemplate.PrimaryVerificationKey as SymmetricVerificationKey).KeyValue);
                                            signingcredentials = new SigningCredentials(tokenSigningKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);
                                        }
                                        else if (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(X509CertTokenVerificationKey))
                                        {
                                            if (signingcredentials == null)
                                            {
                                                X509Certificate2 cert = DynamicEncryption.GetCertificateFromFile(true);
                                                if (cert != null)
                                                {
                                                    signingcredentials = new X509SigningCredentials(cert);
                                                }
                                            }
                                        }
                                        JwtSecurityToken        token   = new JwtSecurityToken(issuer: tokenTemplate.Issuer, audience: tokenTemplate.Audience, notBefore: DateTime.Now.AddMinutes(-5), expires: DateTime.Now.AddMinutes(Properties.Settings.Default.DefaultTokenDuration), signingCredentials: signingcredentials, claims: myclaims);
                                        JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
                                        MyResult.TokenString = handler.WriteToken(token);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(MyResult);
        }
        static void Main(string[] args)
        {
            // Create and cache the Media Services credentials in a static class variable.
            _cachedCredentials = new MediaServicesCredentials(
                _mediaServicesAccountName,
                _mediaServicesAccountKey);
            // Used the cached credentials to create CloudMediaContext.
            _context = new CloudMediaContext(_cachedCredentials);

            bool   tokenRestriction    = false;
            string tokenTemplateString = null;

            IAsset asset = UploadFileAndCreateAsset(_singleMP4File);

            Console.WriteLine("Uploaded asset: {0}", asset.Id);

            IAsset encodedAsset = EncodeToAdaptiveBitrateMP4Set(asset);

            Console.WriteLine("Encoded asset: {0}", encodedAsset.Id);

            IContentKey key = CreateCommonTypeContentKey(encodedAsset);

            Console.WriteLine("Created key {0} for the asset {1} ", key.Id, encodedAsset.Id);
            Console.WriteLine("PlayReady License Key delivery URL: {0}", key.GetKeyDeliveryUrl(ContentKeyDeliveryType.PlayReadyLicense));
            Console.WriteLine();

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

            Console.WriteLine("Added authorization policy: {0}", key.AuthorizationPolicyId);
            Console.WriteLine();

            CreateAssetDeliveryPolicy(encodedAsset, key);
            Console.WriteLine("Created asset delivery policy. \n");
            Console.WriteLine();

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

                // Generate a test token based on the the data in the given TokenRestrictionTemplate.
                // Note, you need to pass the key id Guid because we specified
                // TokenClaim.ContentKeyIdentifierClaim in during the creation of TokenRestrictionTemplate.
                Guid   rawkey    = EncryptionUtils.GetKeyIdAsGuid(key.Id);
                string testToken = TokenRestrictionTemplateSerializer.GenerateTestToken(tokenTemplate, null, rawkey, DateTime.UtcNow.AddDays(365));
                Console.WriteLine("The authorization token is:\nBearer {0}", testToken);
                Console.WriteLine();
            }

            // You can use the http://smf.cloudapp.net/healthmonitor player
            // to test the smoothStreamURL URL.
            //
            string url = GetStreamingOriginLocator(encodedAsset);

            Console.WriteLine("Encrypted Smooth Streaming URL: {0}/manifest", url);


            Console.ReadLine();
        }
 public void InputMissingPrimaryKeyShouldNotThrow()
 {
     string tokenTemplate = "<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>GG07fDPZ+HMD2vcoknMqYjEJMb7LSq8zUmdCYMvRCevnQK//ilbhODO/FydMrHiwZGmI6XywvOOU7SSzRPlI3Q==</KeyValue></TokenVerificationKey></AlternateVerificationKeys><Audience>http://sampleaudience/</Audience><Issuer>http://sampleissuerurl/</Issuer><RequiredClaims><TokenClaim><ClaimType>urn:microsoft:azure:mediaservices:contentkeyidentifier</ClaimType><ClaimValue i:nil=\"true\" /></TokenClaim><TokenClaim><ClaimType>urn:myservice:claims:rental</ClaimType><ClaimValue>true</ClaimValue></TokenClaim></RequiredClaims></TokenRestrictionTemplate>";
     TokenRestrictionTemplate template = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplate);
 }
        static void Main(string[] args)
        {
            AzureAdTokenCredentials tokenCredentials =
                new AzureAdTokenCredentials(_AADTenantDomain,
                                            new AzureAdClientSymmetricKey(_AMSClientId, _AMSClientSecret),
                                            AzureEnvironments.AzureCloudEnvironment);

            var tokenProvider = new AzureAdTokenProvider(tokenCredentials);

            _context = new CloudMediaContext(new Uri(_RESTAPIEndpoint), tokenProvider);

            bool   tokenRestriction    = false;
            string tokenTemplateString = null;

            IAsset asset = UploadFileAndCreateAsset(_singleMP4File);

            Console.WriteLine("Uploaded asset: {0}", asset.Id);

            IAsset encodedAsset = EncodeToAdaptiveBitrateMP4Set(asset);

            Console.WriteLine("Encoded asset: {0}", encodedAsset.Id);

            IContentKey key = CreateCommonCBCTypeContentKey(encodedAsset);

            Console.WriteLine("Created key {0} for the asset {1} ", key.Id, encodedAsset.Id);
            Console.WriteLine("FairPlay License Key delivery URL: {0}", key.GetKeyDeliveryUrl(ContentKeyDeliveryType.FairPlay));
            Console.WriteLine();

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

            Console.WriteLine("Added authorization policy: {0}", key.AuthorizationPolicyId);
            Console.WriteLine();

            CreateAssetDeliveryPolicy(encodedAsset, key);
            Console.WriteLine("Created asset delivery policy. \n");
            Console.WriteLine();

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

                // Generate a test token based on the the data in the given TokenRestrictionTemplate.
                // Note, you need to pass the key id Guid because we specified
                // TokenClaim.ContentKeyIdentifierClaim in during the creation of TokenRestrictionTemplate.
                Guid   rawkey    = EncryptionUtils.GetKeyIdAsGuid(key.Id);
                string testToken = TokenRestrictionTemplateSerializer.GenerateTestToken(tokenTemplate, null, rawkey,
                                                                                        DateTime.UtcNow.AddDays(365));
                Console.WriteLine("The authorization token is:\nBearer {0}", testToken);
                Console.WriteLine();
            }

            string url = GetStreamingOriginLocator(encodedAsset);

            Console.WriteLine("Encrypted HLS URL: {0}/manifest(format=m3u8-aapl)", url);

            Console.ReadLine();
        }
        private void DoDisplayAuthorizationPolicyOption()
        {
            if (listViewAutPolOptions.SelectedItems.Count > 0 && SelectedPolicy != null)
            {
                dataGridViewAutPolOption.Rows.Clear();
                dataGridViewAutPolOption.ColumnCount = 2;
                dataGridViewAutPolOption.Columns[0].DefaultCellStyle.BackColor = Color.Gainsboro;


                IContentKeyAuthorizationPolicyOption option = SelectedPolicy.Options.Skip(listViewAutPolOptions.SelectedIndices[0]).Take(1).FirstOrDefault();
                if (option != null) // Token option
                {
                    dataGridViewAutPolOption.Rows.Add("Name", option.Name != null ? option.Name : "<no name>");
                    dataGridViewAutPolOption.Rows.Add("Id", option.Id);

                    // Key delivery configuration

                    int i = dataGridViewAutPolOption.Rows.Add("KeyDeliveryConfiguration", "<null>");
                    if (option.KeyDeliveryConfiguration != null)
                    {
                        DataGridViewButtonCell btn = new DataGridViewButtonCell();
                        dataGridViewAutPolOption.Rows[i].Cells[1]       = btn;
                        dataGridViewAutPolOption.Rows[i].Cells[1].Value = "See value";
                        dataGridViewAutPolOption.Rows[i].Cells[1].Tag   = option.KeyDeliveryConfiguration;
                    }

                    dataGridViewAutPolOption.Rows.Add("KeyDeliveryType", option.KeyDeliveryType);

                    List <ContentKeyAuthorizationPolicyRestriction> objList_restriction = option.Restrictions;
                    foreach (var restriction in objList_restriction)
                    {
                        dataGridViewAutPolOption.Rows.Add("Restriction Name", restriction.Name);
                        dataGridViewAutPolOption.Rows.Add("Restriction KeyRestrictionType", (ContentKeyRestrictionType)restriction.KeyRestrictionType);

                        if (restriction.Requirements != null)
                        {
                            // Restriction Requirements
                            i = dataGridViewAutPolOption.Rows.Add("Restriction Requirements", "<null>");
                            if (restriction.Requirements != null)
                            {
                                DataGridViewButtonCell btn2 = new DataGridViewButtonCell();
                                dataGridViewAutPolOption.Rows[i].Cells[1]       = btn2;
                                dataGridViewAutPolOption.Rows[i].Cells[1].Value = "See value";
                                dataGridViewAutPolOption.Rows[i].Cells[1].Tag   = restriction.Requirements;

                                TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(restriction.Requirements);
                                dataGridViewAutPolOption.Rows.Add("Token Type", tokenTemplate.TokenType);

                                i = dataGridViewAutPolOption.Rows.Add("Primary Verification Key", "<null>");
                                if (tokenTemplate.PrimaryVerificationKey != null)
                                {
                                    dataGridViewAutPolOption.Rows.Add("Token Verification Key Type", (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey)) ? "Symmetric" : "Asymmetric (X509)");
                                    if (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey))
                                    {
                                        var verifkey = (SymmetricVerificationKey)tokenTemplate.PrimaryVerificationKey;
                                        btn2 = new DataGridViewButtonCell();
                                        dataGridViewAutPolOption.Rows[i].Cells[1]       = btn2;
                                        dataGridViewAutPolOption.Rows[i].Cells[1].Value = "See key value";
                                        dataGridViewAutPolOption.Rows[i].Cells[1].Tag   = Convert.ToBase64String(verifkey.KeyValue);
                                    }
                                }


                                foreach (var verifkey in tokenTemplate.AlternateVerificationKeys)
                                {
                                    i = dataGridViewAutPolOption.Rows.Add("Alternate Verification Key", "<null>");
                                    if (verifkey != null)
                                    {
                                        dataGridViewAutPolOption.Rows.Add("Token Verification Key Type", (verifkey.GetType() == typeof(SymmetricVerificationKey)) ? "Symmetric" : "Asymmetric (X509)");
                                        if (verifkey.GetType() == typeof(SymmetricVerificationKey))
                                        {
                                            var verifkeySym = (SymmetricVerificationKey)verifkey;
                                            btn2 = new DataGridViewButtonCell();
                                            dataGridViewAutPolOption.Rows[i].Cells[1]       = btn2;
                                            dataGridViewAutPolOption.Rows[i].Cells[1].Value = "See key value";
                                            dataGridViewAutPolOption.Rows[i].Cells[1].Tag   = Convert.ToBase64String(verifkeySym.KeyValue);
                                        }
                                    }
                                }

                                if (tokenTemplate.OpenIdConnectDiscoveryDocument != null)
                                {
                                    dataGridViewAutPolOption.Rows.Add("OpenId Connect Discovery Document Uri", tokenTemplate.OpenIdConnectDiscoveryDocument.OpenIdDiscoveryUri);
                                }
                                dataGridViewAutPolOption.Rows.Add("Token Audience", tokenTemplate.Audience);
                                dataGridViewAutPolOption.Rows.Add("Token Issuer", tokenTemplate.Issuer);
                                foreach (var claim in tokenTemplate.RequiredClaims)
                                {
                                    dataGridViewAutPolOption.Rows.Add("Required Claim, Type", claim.ClaimType);
                                    dataGridViewAutPolOption.Rows.Add("Required Claim, Value", claim.ClaimValue);
                                }
                            }
                        }
                    }
                }
            }
        }
Beispiel #27
0
        public ActionResult Index()
        {
            _cachedCredentials = new MediaServicesCredentials(
                _mediaServicesAccountName,
                _mediaServicesAccountKey);
            myContext = new CloudMediaContext(_cachedCredentials);

            // Use a LINQ Select query to get an asset.
            var assetInstance =
                from a in myContext.Assets
                where a.Name == assetName
                select a;
            // Reference the asset as an IAsset.
            IAsset      myAsset = assetInstance.FirstOrDefault();
            IContentKey key     = myAsset.ContentKeys[0];
            IContentKeyAuthorizationPolicy AutPol = myContext.ContentKeyAuthorizationPolicies.Where(a => a.Id == key.AuthorizationPolicyId).FirstOrDefault();
            //IContentKeyAuthorizationPolicyOption AutPolOption = AutPol.Options.Skip(0).FirstOrDefault();
            IContentKeyAuthorizationPolicyOption AutPolOption = AutPol.Options.Where(o => (ContentKeyRestrictionType)o.Restrictions.FirstOrDefault().KeyRestrictionType == ContentKeyRestrictionType.TokenRestricted).FirstOrDefault();

            string tokenTemplateString             = AutPolOption.Restrictions.FirstOrDefault().Requirements;
            TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString);
            Guid     rawkey    = EncryptionUtils.GetKeyIdAsGuid(key.Id);
            DateTime StartDate = DateTime.Now.AddMinutes(-5);
            DateTime EndDate   = DateTime.Now.AddMinutes(TokenDuration);

            if (tokenTemplate.TokenType == TokenType.SWT) //SWT
            {
                tokenString = TokenRestrictionTemplateSerializer.GenerateTestToken(tokenTemplate, null, rawkey, EndDate);
            }
            else // JWT
            {
                IList <Claim> myclaims = null;
                bool          IsAddContentKeyIdentifierClaim = false;
                myclaims = GetTokenRequiredClaims(tokenTemplate, out IsAddContentKeyIdentifierClaim);
                //List<Claim> myclaims = null;
                //myclaims = new List<Claim>();
                //myclaims.Add(new Claim(TokenClaim.ContentKeyIdentifierClaimType, rawkey.ToString()));

                SigningCredentials signingcredentials = null;

                if (IsAddContentKeyIdentifierClaim)
                {
                    myclaims.Add(new Claim(TokenClaim.ContentKeyIdentifierClaimType, rawkey.ToString()));
                }

                //if (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey))
                //{
                InMemorySymmetricSecurityKey tokenSigningKey = new InMemorySymmetricSecurityKey((tokenTemplate.PrimaryVerificationKey as SymmetricVerificationKey).KeyValue);
                signingcredentials = new SigningCredentials(tokenSigningKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);
                //}
                //else if (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(X509CertTokenVerificationKey))
                //{
                //X509Certificate2 cert = form.GetX509Certificate;
                //if (cert != null) signingcredentials = new X509SigningCredentials(cert);
                //}

                string AudienceUri = tokenTemplate.Audience.ToString();
                //JwtSecurityToken token = new JwtSecurityToken(issuer: IssuerUri, audience: AudienceUri, notBefore: StartDate, expires: EndDate, signingCredentials: signingcredentials, claims: myclaims);
                JwtSecurityToken        token   = new JwtSecurityToken(issuer: tokenTemplate.Issuer, audience: tokenTemplate.Audience, notBefore: StartDate, expires: EndDate, signingCredentials: signingcredentials, claims: myclaims);
                JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
                //ViewBag.TokenString = HttpUtility.UrlEncode("Bearer " + handler.WriteToken(token));
                ViewBag.TokenString = "Bearer " + handler.WriteToken(token);
            }

            return(View());
        }
        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);
            }
        }