public TokenServiceConfiguration() : base()
        {
            Tracing.Information("Configuring token service");
            Container.Current.SatisfyImportsOnce(this);
            GlobalConfiguration = ConfigurationRepository.Configuration;

            SecurityTokenService = typeof(TokenService);
            DefaultTokenLifetime = TimeSpan.FromHours(GlobalConfiguration.DefaultTokenLifetime);
            MaximumTokenLifetime = TimeSpan.FromDays(GlobalConfiguration.MaximumTokenLifetime);
            DefaultTokenType = GlobalConfiguration.DefaultTokenType;

            TokenIssuerName = GlobalConfiguration.IssuerUri;
            SigningCredentials = new X509SigningCredentials(ConfigurationRepository.SigningCertificate.Certificate);

            if (GlobalConfiguration.EnableDelegation)
            {
                Tracing.Information("Configuring identity delegation support");

                try
                {
                    var actAsRegistry = new ConfigurationBasedIssuerNameRegistry();
                    actAsRegistry.AddTrustedIssuer(ConfigurationRepository.SigningCertificate.Certificate.Thumbprint, GlobalConfiguration.IssuerUri);

                    var actAsHandlers = SecurityTokenHandlerCollectionManager["ActAs"];
                    actAsHandlers.Configuration.IssuerNameRegistry = actAsRegistry;
                    actAsHandlers.Configuration.AudienceRestriction.AudienceMode = AudienceUriMode.Never;
                }
                catch (Exception ex)
                {
                    Tracing.Error("Error configuring identity delegation");
                    Tracing.Error(ex.ToString());
                    throw;
                }
            }
        }
        public static JwtSecurityToken CreateToken(
            string issuer = null,
            string audience = null,
            IEnumerable<string> scope = null,
            int ttl = 360,
            List<Claim> additionalClaims = null,
            X509Certificate2 signingCertificate = null)
        {
            if (additionalClaims == null)
            {
                additionalClaims = new List<Claim>();
            }

            if (scope != null && scope.Any())
            {
                scope.ToList().ForEach(s => additionalClaims.Add(new Claim("scope", s)));
            }

            var credential = new X509SigningCredentials(signingCertificate ?? DefaultSigningCertificate);

            var token = new JwtSecurityToken(
                issuer ?? DefaultIssuer,
                audience ?? DefaultAudience,
                additionalClaims,
                DateTime.UtcNow,
                DateTime.UtcNow.AddSeconds(ttl),
                credential);

            token.Header.Add(
                "kid", Base64Url.Encode(credential.Certificate.GetCertHash()));

            return token;
        }
        public ActionResult GetAccessToken(string code)
        {
            var query = new Dictionary<string, string>();
            query.Add("client_id", Constants.GITHUB_CLIENT_ID);
            query.Add("client_secret", Constants.GITHUB_CLIENT_SEC);
            query.Add("code", code);
            query.Add("state", Constants.GITHUB_OAUTH_STATE);

            // send request
            JObject resp = Utility.MakeJsonHttpRequest(Constants.GITHUB_AK_URL, query);
            string accessToken = (string)resp["access_token"];

            // call sts and return
            // build cliam
            var claim = new ClaimsPrincipal();
            var id = new ClaimsIdentity();
            id.AddClaim(new Claim(Constants.CLAIM_TYPE_GITHUB_AK, accessToken));
            claim.AddIdentity(id);

            // send claim
            var sigingCredentials = new X509SigningCredentials(Utility.GetCertificate(Constants.CERTIFICATE_NAME));

            var config = new SecurityTokenServiceConfiguration(Constants.ISSUER_NAME, sigingCredentials);
            var sts = new CustomSecurityTokenService(config);

            var requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(Request.Url);
            var responesMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, claim, sts);

            var formData = responesMessage.WriteFormPost();
            return new ContentResult() { Content = formData, ContentType = "text/html" };
        }
        public OkSecurityTokenServiceConfiguration()
        {
            TokenIssuerName = OkClaims.IssuerName;
            string signingCertificatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Constants.SigningCertificate);
            var signignCert = new X509Certificate2(signingCertificatePath, Constants.SigningCertificatePassword, X509KeyStorageFlags.PersistKeySet);
            SigningCredentials = new X509SigningCredentials(signignCert);
            ServiceCertificate = signignCert;

            SecurityTokenService = typeof (OkSecurityTokenService);
        }
Ejemplo n.º 5
0
 private static string ProcessSignIn(Uri url, ClaimsPrincipal user)
 {
     var requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(url);
       var signingCredentials = new X509SigningCredentials(CustomSecurityTokenService.GetCertificate(ConfigurationManager.AppSettings["SigningCertificateName"]));
       var config = new SecurityTokenServiceConfiguration(ConfigurationManager.AppSettings["IssuerName"], signingCredentials);
       config.SecurityTokenHandlers.Clear();
       config.SecurityTokenHandlers.AddOrReplace(new CustomUsernameTokenHandler());
       var sts = new CustomSecurityTokenService(config);
       var responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, user, sts);
       return responseMessage.WriteFormPost();
 }
Ejemplo n.º 6
0
        static string GetClientAssertion(string tenantId, string clientId, X509Certificate2 cert)
        {
            var claims = new List<Claim>();
            claims.Add(new Claim("sub", clientId));

            var handler = new JwtSecurityTokenHandler();
            var credentials = new X509SigningCredentials(cert);
            return handler.CreateToken(
                issuer: clientId,
                audience: String.Format(TokenEndpoint, tenantId), 
                subject: new ClaimsIdentity(claims), 
                signingCredentials: credentials).RawData;
        }
Ejemplo n.º 7
0
        internal static string CreteJWTToken()
        {
            var cert = new X509SigningCredentials(SecurityHelper.GetCertificate());
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, "Hulk"),
                new Claim(ClaimTypes.Spn, "superhero"),
                new Claim(ClaimTypes.Thumbprint, cert.Certificate.GetCertHashString()),
            };

            var token = new JwtSecurityToken(SecurityHelper.CertificateValidIssuer, SecurityHelper.CertificateValidAudience, claims, DateTime.UtcNow, DateTime.UtcNow.AddSeconds(10), cert);
            var tokenHandler = new JwtSecurityTokenHandler();
            var tokenData = tokenHandler.WriteToken(token);

            return tokenData;
        }
        public void Security_X509CertificateTokenVerificationFact()
        {
            var issuer = "http://katanatesting.com/";
            var sentIdentity = new ClaimsIdentity("CustomJwt", "MyNameClaimType", "MyRoleClaimType");
            sentIdentity.AddClaims(new Claim[] { new Claim("MyNameClaimType", "TestUser"), new Claim("MyRoleClaimType", "Administrator") });
            for (int i = 0; i < 5; i++)
            {
                sentIdentity.AddClaim(new Claim("ClaimId" + i.ToString(), i.ToString()));
            }

            var authProperties = new AuthenticationProperties();
            var sentTicket = new AuthenticationTicket(sentIdentity, authProperties);

            var signingCertificate = GetACertificateWithPrivateKey();
            var signingCredentials = new X509SigningCredentials(signingCertificate);
            var tokenValidationParameters = new TokenValidationParameters() { ValidAudience = issuer, SaveSigninToken = true, AuthenticationType = sentIdentity.AuthenticationType };
            var formatter = new JwtFormat(tokenValidationParameters, new X509CertificateSecurityTokenProvider(issuer, signingCertificate));
            formatter.TokenHandler = new JwtSecurityTokenHandler();

            var protectedtext = SecurityUtils.CreateJwtToken(sentTicket, issuer, signingCredentials);

            //Receive part
            var receivedTicket = formatter.Unprotect(protectedtext);

            var receivedClaims = receivedTicket.Identity.Claims;
            Assert.Equal<string>("CustomJwt", receivedTicket.Identity.AuthenticationType);
            Assert.Equal<string>(ClaimsIdentity.DefaultNameClaimType, receivedTicket.Identity.NameClaimType);
            Assert.Equal<string>(ClaimsIdentity.DefaultRoleClaimType, receivedTicket.Identity.RoleClaimType);
            Assert.NotNull(receivedTicket.Identity.BootstrapContext);
            Assert.NotNull(((BootstrapContext)receivedTicket.Identity.BootstrapContext).Token);
            Assert.Equal<string>(issuer, receivedClaims.Where<Claim>(claim => claim.Type == "iss").FirstOrDefault().Value);
            Assert.Equal<string>(issuer, receivedClaims.Where<Claim>(claim => claim.Type == "aud").FirstOrDefault().Value);
            Assert.NotEmpty(receivedClaims.Where<Claim>(claim => claim.Type == "exp").FirstOrDefault().Value);

            for (int i = 0; i < 5; i++)
            {
                sentIdentity.AddClaim(new Claim("ClaimId" + i.ToString(), i.ToString()));
                Assert.Equal<string>(i.ToString(), receivedClaims.Where<Claim>(claim => claim.Type == "ClaimId" + i.ToString()).FirstOrDefault().Value);
            }

            Assert.Equal<string>("TestUser", receivedClaims.Where<Claim>(claim => claim.Type == ClaimsIdentity.DefaultNameClaimType).FirstOrDefault().Value);
            Assert.Equal<string>("Administrator", receivedClaims.Where<Claim>(claim => claim.Type == ClaimsIdentity.DefaultRoleClaimType).FirstOrDefault().Value);
            Assert.NotEmpty(receivedClaims.Where<Claim>(claim => claim.Type == "iat").FirstOrDefault().Value);
            Assert.NotEmpty(receivedClaims.Where<Claim>(claim => claim.Type == "jti").FirstOrDefault().Value);
        }
        public byte[] GetFederationMetadata(Uri passiveSignInUrl, Uri identifier, X509Certificate2 signingCertificate)
        {
            var credentials = new X509SigningCredentials(signingCertificate);

            // Figure out the hostname exposed from Azure and what port the service is listening on
            var realm = new EndpointAddress(identifier);
            var passiveEndpoint = new EndpointReference(passiveSignInUrl.AbsoluteUri);

            // Create metadata document for relying party
            EntityDescriptor entity = new EntityDescriptor(new EntityId(realm.Uri.AbsoluteUri));
            SecurityTokenServiceDescriptor sts = new SecurityTokenServiceDescriptor();
            entity.RoleDescriptors.Add(sts);

            // Add STS's signing key
            KeyDescriptor signingKey = new KeyDescriptor(credentials.SigningKeyIdentifier);
            signingKey.Use = KeyType.Signing;
            sts.Keys.Add(signingKey);

            // Add offered claim types
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.AuthenticationMethod));
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.AuthenticationInstant));
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Name));

            // Add passive federation endpoint
            sts.PassiveRequestorEndpoints.Add(passiveEndpoint);

            // Add supported protocols
            sts.ProtocolsSupported.Add(new Uri(WSFederationConstants.Namespace));

            // Add passive STS endpoint
            sts.SecurityTokenServiceEndpoints.Add(passiveEndpoint);

            // Set credentials with which to sign the metadata
            entity.SigningCredentials = credentials;

            // Serialize the metadata and convert it to an XElement
            MetadataSerializer serializer = new MetadataSerializer();
            MemoryStream stream = new MemoryStream();
            serializer.WriteMetadata(stream, entity);
            stream.Flush();

            return stream.ToArray();
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="JwtHeader"/> class. With the Header Parameters as follows:
        /// <para>{ { typ, JWT }, { alg, Mapped( <see cref="System.IdentityModel.Tokens.SigningCredentials.SignatureAlgorithm"/> } }
        /// See: Algorithm Mapping below.</para>
        /// </summary>
        /// <param name="signingCredentials">The <see cref="SigningCredentials"/> that will be or were used to sign the <see cref="JwtSecurityToken"/>.</param>
        /// <remarks>
        /// <para>For each <see cref="SecurityKeyIdentifierClause"/> in signingCredentials.SigningKeyIdentifier</para>
        /// <para>if the clause  is a <see cref="NamedKeySecurityKeyIdentifierClause"/> Header Parameter { clause.Name, clause.KeyIdentifier } will be added.</para>
        /// <para>For example, if clause.Name == 'kid' and clause.KeyIdentifier == 'SecretKey99'. The JSON object { kid, SecretKey99 } would be added.</para>
        /// <para>In addition, if the <see cref="SigningCredentials"/> is a <see cref="X509SigningCredentials"/> the JSON object { x5t, Base64UrlEncoded( <see cref="X509Certificate.GetCertHashString()"/> } will be added.</para>
        /// <para>This simplifies the common case where a X509Certificate is used.</para>
        /// <para>================= </para>
        /// <para>Algorithm Mapping</para>
        /// <para>================= </para>
        /// <para><see cref="System.IdentityModel.Tokens.SigningCredentials.SignatureAlgorithm"/> describes the algorithm that is discoverable by the CLR runtime.</para>
        /// <para>The  { alg, 'value' } placed in the header reflects the JWT specification.</para>
        /// <see cref="JwtSecurityTokenHandler.OutboundAlgorithmMap"/> contains a signature mapping where the 'value' above will be translated according to this mapping.
        /// <para>Current mapping is:</para>
        /// <para>&#160;&#160;&#160;&#160;'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256' => 'RS256'</para>
        /// <para>&#160;&#160;&#160;&#160;'http://www.w3.org/2001/04/xmldsig-more#hmac-sha256' => 'HS256'</para>
        /// </remarks>
        public JwtHeader(SigningCredentials signingCredentials = null)
            : base(StringComparer.Ordinal)
        {
            this.Add(JwtConstants.ReservedHeaderParameters.Type, JwtConstants.HeaderType);

            if (signingCredentials != null)
            {
                this.signingCredentials = signingCredentials;

                string algorithm = signingCredentials.SignatureAlgorithm;
                if (JwtSecurityTokenHandler.OutboundAlgorithmMap.ContainsKey(signingCredentials.SignatureAlgorithm))
                {
                    algorithm = JwtSecurityTokenHandler.OutboundAlgorithmMap[algorithm];
                }

                this.Add(JwtConstants.ReservedHeaderParameters.Algorithm, algorithm);
                if (signingCredentials.SigningKeyIdentifier != null)
                {
                    foreach (SecurityKeyIdentifierClause clause in signingCredentials.SigningKeyIdentifier)
                    {
                        NamedKeySecurityKeyIdentifierClause namedKeyClause = clause as NamedKeySecurityKeyIdentifierClause;
                        if (namedKeyClause != null)
                        {
                            this.Add(namedKeyClause.Name, namedKeyClause.KeyIdentifier);
                        }
                    }
                }

                X509SigningCredentials x509SigningCredentials = signingCredentials as X509SigningCredentials;
                if (x509SigningCredentials != null && x509SigningCredentials.Certificate != null)
                {
                    this.Add(JwtConstants.ReservedHeaderParameters.X509CertificateThumbprint, Base64UrlEncoder.Encode(x509SigningCredentials.Certificate.GetCertHash()));
                }
            }
            else
            {
                this.Add(JwtConstants.ReservedHeaderParameters.Algorithm, JwtConstants.Algorithms.NONE);
            }
        }
        private void DoDynamicEncryptionAndKeyDeliveryWithPlayReady(List<IAsset> SelectedAssets, AddDynamicEncryptionFrame1 form1, AddDynamicEncryptionFrame2_PlayReadyKeyConfig form2_PlayReady, List<AddDynamicEncryptionFrame3> form3list, List<AddDynamicEncryptionFrame4_PlayReadyLicense> form4PlayReadyLicenseList, bool DisplayUI)
        {
            bool ErrorCreationKey = false;
            bool reusekey = false;
            bool firstkeycreation = true;
            IContentKey formerkey = null;

            if (!form2_PlayReady.ContentKeyRandomGeneration)  // user want to manually enter the key and did not provide a seed
            {
                // if the key already exists in the account (same key id), let's 
                formerkey = SelectedAssets.FirstOrDefault().GetMediaContext().ContentKeys.Where(c => c.Id == Constants.ContentKeyIdPrefix + form2_PlayReady.PlayReadyKeyId.ToString()).FirstOrDefault();
                if (formerkey != null)
                {
                    if (DisplayUI && MessageBox.Show("A Content key with the same Key Id exists already in the account.\nDo you want to try to replace it?\n(If not, the existing key will be used)", "Content key Id", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        // user wants to replace the key
                        try
                        {
                            formerkey.Delete();
                        }
                        catch (Exception e)
                        {
                            // Add useful information to the exception
                            TextBoxLogWriteLine("There is a problem when deleting the content key {0}.", formerkey.Id, true);
                            TextBoxLogWriteLine(e);
                            TextBoxLogWriteLine("The former key will be reused.", true);
                            reusekey = true;
                        }
                    }
                    else
                    {
                        reusekey = true;
                    }
                }
            }


            foreach (IAsset AssetToProcess in SelectedAssets)
            {
                if (AssetToProcess != null)
                {
                    IContentKey contentKey = null;
                    var contentkeys = AssetToProcess.ContentKeys.Where(c => c.ContentKeyType == form1.GetContentKeyType);
                    // special case, no dynamic encryption, goal is to setup key auth policy. CENC key is selected

                    if (contentkeys.Count() == 0) // no content key existing so we need to create one
                    {
                        ErrorCreationKey = false;

                        if (form1.GetNumberOfAuthorizationPolicyOptions > 0 && (form2_PlayReady.ContentKeyRandomGeneration)) // Azure will deliver the license and user want to auto generate the key, so we can create a key with a random content key
                        {
                            try
                            {
                                contentKey = DynamicEncryption.CreateCommonTypeContentKey(AssetToProcess, _context);
                            }
                            catch (Exception e)
                            {
                                // Add useful information to the exception
                                TextBoxLogWriteLine("There is a problem when creating the content key for '{0}'.", AssetToProcess.Name, true);
                                TextBoxLogWriteLine(e);
                                ErrorCreationKey = true;
                            }
                            if (!ErrorCreationKey)
                            {
                                TextBoxLogWriteLine("Created key {0} for asset '{1}'.", contentKey.Id, AssetToProcess.Name);
                            }

                        }
                        else // user wants to deliver with an external PlayReady server or want to provide the key, so let's create the key based on what the user input
                        {
                            // if the key does not exist in the account (same key id), let's 
                            if (firstkeycreation && !reusekey)
                            {
                                if (!string.IsNullOrEmpty(form2_PlayReady.PlayReadyKeySeed)) // seed has been given
                                {
                                    Guid keyid = (form2_PlayReady.PlayReadyKeyId == null) ? Guid.NewGuid() : (Guid)form2_PlayReady.PlayReadyKeyId;
                                    byte[] bytecontentkey = CommonEncryption.GeneratePlayReadyContentKey(Convert.FromBase64String(form2_PlayReady.PlayReadyKeySeed), keyid);
                                    try
                                    {
                                        contentKey = DynamicEncryption.CreateCommonTypeContentKey(AssetToProcess, _context, keyid, bytecontentkey);
                                    }
                                    catch (Exception e)
                                    {
                                        // Add useful information to the exception
                                        TextBoxLogWriteLine("There is a problem when creating the content key for '{0}'.", AssetToProcess.Name, true);
                                        TextBoxLogWriteLine(e);
                                        ErrorCreationKey = true;
                                    }
                                    if (!ErrorCreationKey)
                                    {
                                        TextBoxLogWriteLine("Created key {0} for the asset {1} ", contentKey.Id, AssetToProcess.Name);
                                    }

                                }
                                else // no seed given, so content key has been setup
                                {
                                    try
                                    {
                                        contentKey = DynamicEncryption.CreateCommonTypeContentKey(AssetToProcess, _context, (Guid)form2_PlayReady.PlayReadyKeyId, Convert.FromBase64String(form2_PlayReady.PlayReadyContentKey));
                                    }
                                    catch (Exception e)
                                    {
                                        // Add useful information to the exception
                                        TextBoxLogWriteLine("There is a problem when creating the content key for asset '{0}'.", AssetToProcess.Name, true);
                                        TextBoxLogWriteLine(e);
                                        ErrorCreationKey = true;
                                    }
                                    if (!ErrorCreationKey)
                                    {
                                        TextBoxLogWriteLine("Created key {0} for asset '{1}'.", contentKey.Id, AssetToProcess.Name);
                                    }

                                }
                                formerkey = contentKey;
                                firstkeycreation = false;
                            }
                            else
                            {
                                contentKey = formerkey;
                                AssetToProcess.ContentKeys.Add(contentKey);
                                AssetToProcess.Update();
                                TextBoxLogWriteLine("Reusing key {0} for the asset {1} ", contentKey.Id, AssetToProcess.Name);
                            }
                        }
                    }
                    else if (form1.GetNumberOfAuthorizationPolicyOptions == 0)  // user wants to deliver with an external PlayReady server but the key exists already !
                    {
                        TextBoxLogWriteLine("Warning for asset '{0}'. A CENC key already exists. You need to make sure that your external PlayReady server can deliver the license for this asset.", AssetToProcess.Name, true);
                    }
                    else // let's use existing content key
                    {
                        contentKey = contentkeys.FirstOrDefault();
                        TextBoxLogWriteLine("Existing key '{0}' will be used for asset '{1}'.", contentKey.Id, AssetToProcess.Name);
                    }
                    if (form1.GetNumberOfAuthorizationPolicyOptions > 0) // PlayReady license and delivery from Azure Media Services
                    {
                        // let's create the Authorization Policy
                        IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = _context.
                                       ContentKeyAuthorizationPolicies.
                                       CreateAsync("My Authorization Policy").Result;

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

                        foreach (var form3 in form3list)
                        {
                            // let's build the PlayReady license template
                            string PlayReadyLicenseDeliveryConfig = null;
                            ErrorCreationKey = false;
                            try
                            {
                                PlayReadyLicenseDeliveryConfig = form4PlayReadyLicenseList[form3list.IndexOf(form3)].GetLicenseTemplate;
                                // PlayReadyLicenseDeliveryConfig = DynamicEncryption.ConfigurePlayReadyLicenseTemplate(form4PlayReadyLicenseList[form3list.IndexOf(form3)].GetLicenseTemplate);
                            }
                            catch (Exception e)
                            {
                                // Add useful information to the exception
                                TextBoxLogWriteLine("There is a problem when configuring the PlayReady license template.", true);
                                TextBoxLogWriteLine(e);
                                ErrorCreationKey = true;
                            }
                            if (!ErrorCreationKey)
                            {
                                IContentKeyAuthorizationPolicyOption policyOption = null;
                                try
                                {
                                    switch (form3.GetKeyRestrictionType)
                                    {
                                        case ContentKeyRestrictionType.Open:
                                            policyOption = DynamicEncryption.AddOpenAuthorizationPolicyOption(contentKey, ContentKeyDeliveryType.PlayReadyLicense, PlayReadyLicenseDeliveryConfig, _context);
                                            TextBoxLogWriteLine("Created Open authorization policy for the asset {0} ", contentKey.Id, AssetToProcess.Name);
                                            contentKeyAuthorizationPolicy.Options.Add(policyOption);
                                            break;

                                        case ContentKeyRestrictionType.TokenRestricted:
                                            TokenVerificationKey mytokenverifkey = null;
                                            string OpenIdDoc = null;
                                            switch (form3.GetDetailedTokenType)
                                            {
                                                case ExplorerTokenType.SWT:
                                                case ExplorerTokenType.JWTSym:
                                                    mytokenverifkey = new SymmetricVerificationKey(Convert.FromBase64String(form3.SymmetricKey));
                                                    break;

                                                case ExplorerTokenType.JWTOpenID:
                                                    OpenIdDoc = form3.GetOpenIdDiscoveryDocument;
                                                    break;

                                                case ExplorerTokenType.JWTX509:
                                                    mytokenverifkey = new X509CertTokenVerificationKey(form3.GetX509Certificate);
                                                    break;
                                            }

                                            policyOption = DynamicEncryption.AddTokenRestrictedAuthorizationPolicyPlayReady(contentKey, form3.GetAudience, form3.GetIssuer, form3.GetTokenRequiredClaims, form3.AddContentKeyIdentifierClaim, form3.GetTokenType, form3.GetDetailedTokenType, mytokenverifkey, _context, PlayReadyLicenseDeliveryConfig, OpenIdDoc);
                                            TextBoxLogWriteLine("Created Token CENC authorization policy for the asset {0} ", contentKey.Id, AssetToProcess.Name);
                                            contentKeyAuthorizationPolicy.Options.Add(policyOption);

                                            if (form3.GetDetailedTokenType != ExplorerTokenType.JWTOpenID) // not possible to create a test token if OpenId is used
                                            {
                                                // let display a test token
                                                X509SigningCredentials signingcred = null;
                                                if (form3.GetDetailedTokenType == ExplorerTokenType.JWTX509)
                                                {
                                                    signingcred = new X509SigningCredentials(form3.GetX509Certificate);
                                                }

                                                _context = Program.ConnectAndGetNewContext(_credentials); // otherwise cache issues with multiple options
                                                DynamicEncryption.TokenResult testToken = DynamicEncryption.GetTestToken(AssetToProcess, _context, form1.GetContentKeyType, signingcred, policyOption.Id);
                                                TextBoxLogWriteLine("The authorization test token for option #{0} ({1} with Bearer) is:\n{2}", form3list.IndexOf(form3), form3.GetTokenType.ToString(), Constants.Bearer + testToken.TokenString);
                                                System.Windows.Forms.Clipboard.SetText(Constants.Bearer + testToken.TokenString);
                                            }
                                            break;


                                        default:
                                            break;
                                    }
                                }
                                catch (Exception e)
                                {
                                    // Add useful information to the exception
                                    TextBoxLogWriteLine("There is a problem when creating the authorization policy for '{0}'.", AssetToProcess.Name, true);
                                    TextBoxLogWriteLine(e);
                                    ErrorCreationKey = true;
                                }
                            }
                        }
                        contentKeyAuthorizationPolicy.Update();
                    }

                    // Let's create the Asset Delivery Policy now
                    if (form1.GetDeliveryPolicyType != AssetDeliveryPolicyType.None)
                    {
                        IAssetDeliveryPolicy DelPol = null;
                        string name = string.Format("AssetDeliveryPolicy {0} ({1})", form1.GetContentKeyType.ToString(), form1.GetAssetDeliveryProtocol.ToString());
                        ErrorCreationKey = false;
                        try
                        {
                            if (form1.GetNumberOfAuthorizationPolicyOptions > 0) // Licenses delivered by Azure Media Services
                            {
                                DelPol = DynamicEncryption.CreateAssetDeliveryPolicyCENC(AssetToProcess, contentKey, form1.GetAssetDeliveryProtocol, name, _context, null, false, form2_PlayReady.PlayReadyCustomAttributes);
                            }
                            else // Licenses NOT delivered by Azure Media Services but by a third party server
                            {
                                DelPol = DynamicEncryption.CreateAssetDeliveryPolicyCENC(AssetToProcess, contentKey, form1.GetAssetDeliveryProtocol, name, _context, new Uri(form2_PlayReady.PlayReadyLAurl), form2_PlayReady.PlayReadyLAurlEncodeForSL, form2_PlayReady.PlayReadyCustomAttributes);
                            }

                            TextBoxLogWriteLine("Created asset delivery policy '{0}' for asset '{1}'.", DelPol.AssetDeliveryPolicyType, AssetToProcess.Name);
                        }
                        catch (Exception e)
                        {
                            TextBoxLogWriteLine("There is a problem when creating the delivery policy for '{0}'.", AssetToProcess.Name, true);
                            TextBoxLogWriteLine(e);
                            ErrorCreationKey = true;
                        }
                    }

                }
            }
        }
        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;
        }
        public void ConfigOpenIdConnectServer(IAppBuilder app)
        {
            //Load the certificate
            X509Certificate2 certificate;

            // Note: in a real world app, you'd probably prefer storing the X.509 certificate
            // in the user or machine store. To keep this sample easy to use, the certificate
            // is extracted from the Certificate.pfx file embedded in this assembly.
            using (var stream = typeof(Startup).Assembly.GetManifestResourceStream("OwinOpenIdConnectServer.Certificate.pfx"))
            using (var buffer = new MemoryStream())
            {
                stream.CopyTo(buffer);
                buffer.Flush();

                certificate = new X509Certificate2(
                    rawData: buffer.GetBuffer(),
                    password: "******");
            }

            var credentials = new X509SigningCredentials(certificate);

            //Set up OpenIdConnectServer
            /**
             * Following end points already implemented by  OpenIdConnectServer
             * ConfigurationEndpointPath = "/.well-known/openid-configuration"
             * KeysEndpointPath = "/.well-known/jwks"
             * to disable them set two paths to null value
             **/
            app.UseOpenIdConnectServer(
                new OpenIdConnectServerOptions
                {
                    // Bearer
                    AuthenticationType = OpenIdConnectDefaults.AuthenticationType,

                    // This server url
                    Issuer = Paths.OpenIdConnectServerBaseAddress,
                    // Key setting for jwt
                    SigningCredentials = credentials,

                    /**
                 * The request path where client applications will redirect the user-agent
                 * in order to obtain the users consent to issue a token or code.
                 * It must begin with a leading slash, for example,  "/Authorize".
                **/
                    AuthorizationEndpointPath = new PathString("/" + Paths.OpenIdAuthorizePath),

                    /**
                     * The request path client applications directly communicate to obtain the access token.
                     * It must begin with a leading slash, like "/Token".
                     * If the client is issued a client_secret, it must be provided to this endpoint.
                     * **/
                    TokenEndpointPath = new PathString("/" + Paths.OepnIdTokenPath),

                    AccessTokenLifetime = TimeSpan.FromDays(14),
                    IdentityTokenLifetime = TimeSpan.FromMinutes(60),
                    AllowInsecureHttp = true,

                    // Note: see AuthorizationController.cs for more
                    // information concerning ApplicationCanDisplayErrors.
                    ApplicationCanDisplayErrors = true,

                    // Authorization code provider which creates and receives the authorization code, and storing code
                    // Current implementation is just storing the code in mem
                    AuthorizationCodeProvider = new AuthenticationTokenProvider
                    {
                        OnCreate = CreateAuthenticationCode,
                        OnReceive = ReceiveAuthenticationCode,
                    },

                    // Refresh token provider which creates and receives refresh token.
                    // Access token provider should be the same, but interesting thing is in middleware there is fallback for access token creation,
                    //if external access token provider is not present, then it creates a token from ticket as default acccess token, in that case
                    // access token is always returned, but for refresh token it is not so
                    RefreshTokenProvider = new AuthenticationTokenProvider
                    {
                        OnCreate = CreateRefreshToken,
                        OnReceive = ReceiveRefreshToken,
                    },

                    // OpendIdConnectServer provider settings, involving client profile management
                    Provider = new OpenIdConnectServerProvider
                    {
                        OnValidateClientAuthentication = ValidateClientAuthentication,
                        OnValidateClientRedirectUri = ValidateClientRedirectUri,
                        OnGrantClientCredentials = GrantClientCredentials,
                        OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials,
                    }
                }

                );
        }
        private void FetchKeyWithJWTAuth(string audience, string issuer)
        {
            IContentKey contentKey = null;
            IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = null;
            IContentKeyAuthorizationPolicyOption policyOption = null;

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

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

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

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

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

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

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

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

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

                Assert.IsNotNull(keyDeliveryServiceUri);

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

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

                string expectedString = GetString(expectedKey);
                string fetchedString = GetString(key);
                Assert.AreEqual(expectedString, fetchedString);
            }
            finally
            {
                CleanupKeyAndPolicy(contentKey, contentKeyAuthorizationPolicy, policyOption);
            }
        }
        /// <summary>
        /// This method returns the configuration for the token issuance request. The configuration
        /// is represented by the Scope class. In our case, we are only capable of issuing a token for a
        /// single RP identity represented by the EncryptingCertificateName.
        /// </summary>
        /// <param name="principal">The caller's principal.</param>
        /// <param name="request">The incoming RST.</param>
        /// <returns>The scope information to be used for the token issuance.</returns>
        protected override Scope GetScope(IClaimsPrincipal principal, RequestSecurityToken request)
        {
            // TEMP
            //ClaimsUtil.LogClaimsPrincipal(principal, "IdpSts.CustomSecurityTokenService.GetScope");
            CustomTextTraceSource ts = new CustomTextTraceSource("IdpSts.CustomSecurityTokenService.GetScope",
                "MyTraceSource", SourceLevels.Information);

            ValidateAppliesTo(request.AppliesTo);
            
            X509Certificate2 signingCert = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine,
                WebConfigurationManager.AppSettings["SigningCertificateName"]);

            if (signingCert != null)
            {
                ts.TraceInformation("signingCert: " + signingCert.SubjectName);
                ts.TraceInformation("\tthumbPrint: " + signingCert.Thumbprint);
            }
            else
            {
                ts.TraceInformation("signingCert: NULL");
            }

            //SecurityKeyIdentifier signingSki = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] { 
            //        new X509SecurityToken(signingCert).CreateKeyIdentifierClause<X509SubjectKeyIdentifierClause>() });

            SecurityKeyIdentifier signingSki = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] { 
                new X509SecurityToken(signingCert).CreateKeyIdentifierClause<X509RawDataKeyIdentifierClause>() });

            X509SigningCredentials signingCredentialss = new X509SigningCredentials(signingCert, signingSki);

            Scope scope = new Scope(request.AppliesTo.Uri.OriginalString, signingCredentialss);


            //string encryptingCertificateName = "";
            string encryptingCertificateName = WebConfigurationManager.AppSettings["EncryptingCertificateName"];
            if (!string.IsNullOrEmpty(encryptingCertificateName))
            {
                // Important note on setting the encrypting credentials.
                // In a production deployment, you would need to select a certificate that is specific to the RP that is requesting the token.
                // You can examine the 'request' to obtain information to determine the certificate to use. (AppliesTo)

                // Original SV
                //scope.EncryptingCredentials = new X509EncryptingCredentials(CertificateUtil.GetCertificateByCommonName(StoreName.TrustedPeople,
                //    StoreLocation.LocalMachine, request.AppliesTo.Uri.Host));

                // New HoK
                X509Certificate2 cert = CertificateUtil.GetCertificate(StoreName.TrustedPeople,
                    StoreLocation.LocalMachine, encryptingCertificateName);
                var ski = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] 
                    { 
                        //new X509SecurityToken(cert).CreateKeyIdentifierClause<X509SubjectKeyIdentifierClause>()
                        new X509SecurityToken(cert).CreateKeyIdentifierClause<X509ThumbprintKeyIdentifierClause>()
                    }
                );
                X509EncryptingCredentials encryptingCredentials = new X509EncryptingCredentials(cert, ski);

                scope.EncryptingCredentials = encryptingCredentials;
            }
            else
            {
                // If there is no encryption certificate specified, the STS will not perform encryption.
                // This will succeed for tokens that are created without keys (BearerTokens) or asymmetric keys.  Symmetric keys are
                // required to be 'wrapped' and the STS will throw.
                scope.TokenEncryptionRequired = false;

                // Symmetric keys are required to be 'wrapped' or the STS will throw, uncomment the code below to turn off proof key encryption.
                // Turning off proof key encryption is not secure and should not be used in a deployment scenario.

                scope.SymmetricKeyEncryptionRequired = false;
            }

            //ts.TraceInformation("request.RequestType: " + request.RequestType);
            //ts.TraceInformation("request.TokenType: " + request.TokenType);
            //ts.TraceInformation("request.KeyType: " + request.KeyType);
            //ts.TraceInformation("request.KeySizeInBits: " + request.KeySizeInBits);

            //ts.TraceInformation("request.SecondaryParameters.TokenType: " + request.SecondaryParameters.TokenType);
            //ts.TraceInformation("request.SecondaryParameters.KeyType: " + request.SecondaryParameters.KeyType);

            //ts.TraceInformation("Principal Name: " + principal.Identity.Name);

            //if (request.SecondaryParameters != null)
            //{
            //    if (!string.IsNullOrEmpty(request.SecondaryParameters.TokenType))
            //    {
            //        if (string.IsNullOrEmpty(request.TokenType))
            //        {
            //            request.TokenType = request.SecondaryParameters.TokenType;
            //        }
            //    }

            //    if (!string.IsNullOrEmpty(request.SecondaryParameters.KeyType))
            //    {
            //        if (string.IsNullOrEmpty(request.KeyType))
            //        {
            //            request.TokenType = request.SecondaryParameters.KeyType;
            //        }
            //    }

            //    if (StringComparer.Ordinal.Equals(request.KeyType, "http://schemas.microsoft.com/idfx/keytype/bearer"))
            //    {
            //        if (request.KeySizeInBits.HasValue)
            //        {
            //            if (request.KeySizeInBits.Value > 0)
            //            {
            //                string errorMsg = string.Format("The request has a KeySize '{0}' that is greater than 0, which, when specified in the request is the required value for sender-vouches assertions.",
            //                    request.KeySizeInBits.Value);
            //                ts.TraceInformation(errorMsg);

            //                request.KeySizeInBits = new int?(0);
            //            }
            //        }
            //        else
            //        {
            //            // the key size for an assertion with Sender-vouches confirmation must be 0
            //            request.KeySizeInBits = new int?(0);
            //        }

            //        ts.TraceInformation("KeySizeInBits: " + request.KeySizeInBits.Value.ToString());
            //    }
            //}

            //if ((StringComparer.Ordinal.Equals(request.KeyType, "http://schemas.microsoft.com/idfx/keytype/bearer") && request.KeySizeInBits.HasValue) && (request.KeySizeInBits.Value != 0))
            //{
            //    ts.TraceInformation("Still Have problems with KeySize!!!");
            //}


            return scope;
        }
Ejemplo n.º 16
0
 public X509SigningCredentials(X509Certificate2 certificate)
     : this(certificate, X509SigningCredentials.GetSecurityKeyIdentifier(certificate), SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest)
 {
 }
Ejemplo n.º 17
0
 public X509SigningCredentials(X509Certificate2 certificate, string signatureAlgorithm, string digestAlgorithm)
     : this(certificate, X509SigningCredentials.GetSecurityKeyIdentifier(certificate), signatureAlgorithm, digestAlgorithm)
 {
 }
        private void DoDynamicEncryptionWithAES(List<IAsset> SelectedAssets, AddDynamicEncryptionFrame1 form1, AddDynamicEncryptionFrame2_AESKeyConfig form2, AddDynamicEncryptionFrame3_AESDelivery form3_AES, List<AddDynamicEncryptionFrame4> form4list, bool DisplayUI)
        {
            bool ErrorCreationKey = false;
            string aeskey = string.Empty;
            bool firstkeycreation = true;
            Uri aeslaurl = null;
            IContentKey formerkey = null;
            bool reusekey = false;

            if (!form2.ContentKeyRandomGeneration)
            {
                aeskey = form2.AESContentKey;
                aeslaurl = form3_AES.AESLaUrl;
            }


            if (!form2.ContentKeyRandomGeneration && (form2.AESKeyId != null))  // user want to manually enter the cryptography data and key if providedd 
            {
                // if the key already exists in the account (same key id), let's 
                formerkey = SelectedAssets.FirstOrDefault().GetMediaContext().ContentKeys.Where(c => c.Id == Constants.ContentKeyIdPrefix + form2.AESKeyId.ToString()).FirstOrDefault();
                if (formerkey != null)
                {
                    if (DisplayUI && MessageBox.Show("A Content key with the same Key Id exists already in the account.\nDo you want to try to replace it?\n(If not, the existing key will be used)", "Content key Id", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        // user wants to replace the key
                        try
                        {
                            formerkey.Delete();
                        }
                        catch (Exception e)
                        {
                            // Add useful information to the exception
                            TextBoxLogWriteLine("There is a problem when deleting the content key {0}.", formerkey.Id, true);
                            TextBoxLogWriteLine(e);
                            TextBoxLogWriteLine("The former key will be reused.", true);
                            reusekey = true;
                        }
                    }
                    else
                    {
                        reusekey = true;
                    }
                }
            }



            foreach (IAsset AssetToProcess in SelectedAssets)
            {

                if (AssetToProcess != null)
                {
                    IContentKey contentKey = null;

                    var contentkeys = AssetToProcess.ContentKeys.Where(c => c.ContentKeyType == form1.GetContentKeyType);

                    if (contentkeys.Count() == 0) // no content key existing so we need to create one
                    {
                        ErrorCreationKey = false;


                        if (form3_AES.GetNumberOfAuthorizationPolicyOptions > 0 && (form2.ContentKeyRandomGeneration))
                        // Azure will deliver the license and user want to auto generate the key, so we can create a key with a random content key
                        {
                            try
                            {
                                contentKey = DynamicEncryption.CreateEnvelopeTypeContentKey(AssetToProcess);
                            }
                            catch (Exception e)
                            {
                                // Add useful information to the exception
                                TextBoxLogWriteLine("There is a problem when creating the content key for '{0}'.", AssetToProcess.Name, true);
                                TextBoxLogWriteLine(e);
                                ErrorCreationKey = true;
                            }
                            if (!ErrorCreationKey)
                            {
                                TextBoxLogWriteLine("Created key {0} for asset '{1}'.", contentKey.Id, AssetToProcess.Name);
                            }
                        }
                        else // user wants to deliver with an external key server or want to provide some cryptography, so let's create the key based on what the user input
                        {
                            if ((firstkeycreation && !reusekey) || form2.AESKeyId == null) // if we need to generate a new key id for each asset
                            {
                                try
                                {
                                    if ((!form2.ContentKeyRandomGeneration) && !string.IsNullOrEmpty(aeskey)) // user provides custom crypto (key, or key id)
                                    {
                                        contentKey = DynamicEncryption.CreateEnvelopeTypeContentKey(AssetToProcess, Convert.FromBase64String(aeskey), form2.AESKeyId);
                                    }
                                    else // content key if random. Perhaps key id has been provided
                                    {
                                        contentKey = DynamicEncryption.CreateEnvelopeTypeContentKey(AssetToProcess, form2.AESKeyId);
                                    }
                                }
                                catch (Exception e)
                                {
                                    // Add useful information to the exception
                                    TextBoxLogWriteLine("There is a problem when creating the content key for asset '{0}'.", AssetToProcess.Name, true);
                                    TextBoxLogWriteLine(e);
                                    ErrorCreationKey = true;
                                }
                                if (!ErrorCreationKey)
                                {
                                    TextBoxLogWriteLine("Created key {0} for asset '{1}'.", contentKey.Id, AssetToProcess.Name);
                                }

                                formerkey = contentKey;
                                firstkeycreation = false;
                            }
                            else
                            {
                                contentKey = formerkey;
                                AssetToProcess.ContentKeys.Add(contentKey);
                                AssetToProcess.Update();
                                TextBoxLogWriteLine("Reusing key {0} for the asset {1} ", contentKey.Id, AssetToProcess.Name);
                            }
                        }

                    }
                    else if (form3_AES.GetNumberOfAuthorizationPolicyOptions == 0)  // user wants to deliver with an external key server but the key exists already !
                    {
                        TextBoxLogWriteLine("Warning for asset '{0}'. A AES key already exists. You need to make sure that your external key server can deliver the key for this asset.", AssetToProcess.Name, true);
                    }

                    else // let's use existing content key
                    {
                        contentKey = contentkeys.FirstOrDefault();
                        TextBoxLogWriteLine("Existing key {0} will be used for asset {1}.", contentKey.Id, AssetToProcess.Name);
                    }


                    if (form3_AES.GetNumberOfAuthorizationPolicyOptions > 0) // AES Key and delivery from Azure Media Services
                    {

                        // let's create the Authorization Policy
                        IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = _context.
                                       ContentKeyAuthorizationPolicies.
                                       CreateAsync("Authorization Policy").Result;

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


                        foreach (var form3 in form4list)
                        {
                            IContentKeyAuthorizationPolicyOption policyOption = null;
                            ErrorCreationKey = false;
                            try
                            {
                                switch (form3.GetKeyRestrictionType)
                                {
                                    case ContentKeyRestrictionType.Open:

                                        policyOption = DynamicEncryption.AddOpenAuthorizationPolicyOption(contentKey, ContentKeyDeliveryType.BaselineHttp, null, _context);
                                        TextBoxLogWriteLine("Created Open authorization policy for the asset {0} ", contentKey.Id, AssetToProcess.Name);
                                        contentKeyAuthorizationPolicy.Options.Add(policyOption);
                                        break;

                                    case ContentKeyRestrictionType.TokenRestricted:
                                        TokenVerificationKey mytokenverifkey = null;
                                        string OpenIdDoc = null;
                                        switch (form3.GetDetailedTokenType)
                                        {
                                            case ExplorerTokenType.SWT:
                                            case ExplorerTokenType.JWTSym:
                                                mytokenverifkey = new SymmetricVerificationKey(Convert.FromBase64String(form3.SymmetricKey));
                                                break;

                                            case ExplorerTokenType.JWTOpenID:
                                                OpenIdDoc = form3.GetOpenIdDiscoveryDocument;
                                                break;

                                            case ExplorerTokenType.JWTX509:
                                                mytokenverifkey = new X509CertTokenVerificationKey(form3.GetX509Certificate);
                                                break;
                                        }

                                        policyOption = DynamicEncryption.AddTokenRestrictedAuthorizationPolicyAES(contentKey, form3.GetAudience, form3.GetIssuer, form3.GetTokenRequiredClaims, form3.AddContentKeyIdentifierClaim, form3.GetTokenType, form3.GetDetailedTokenType, mytokenverifkey, _context, OpenIdDoc);
                                        TextBoxLogWriteLine("Created Token AES authorization policy for the asset {0} ", contentKey.Id, AssetToProcess.Name);
                                        contentKeyAuthorizationPolicy.Options.Add(policyOption);

                                        if (form3.GetDetailedTokenType != ExplorerTokenType.JWTOpenID) // not possible to create a test token if OpenId is used
                                        {
                                            // let display a test token
                                            X509SigningCredentials signingcred = null;
                                            if (form3.GetDetailedTokenType == ExplorerTokenType.JWTX509)
                                            {
                                                signingcred = new X509SigningCredentials(form3.GetX509Certificate);
                                            }

                                            _context = Program.ConnectAndGetNewContext(_credentials); // otherwise cache issues with multiple options
                                            DynamicEncryption.TokenResult testToken = DynamicEncryption.GetTestToken(AssetToProcess, _context, form1.GetContentKeyType, signingcred, policyOption.Id);
                                            TextBoxLogWriteLine("The authorization test token for option #{0} ({1} with Bearer) is:\n{2}", form4list.IndexOf(form3), form3.GetTokenType.ToString(), Constants.Bearer + testToken.TokenString);
                                            System.Windows.Forms.Clipboard.SetText(Constants.Bearer + testToken.TokenString);

                                        }
                                        break;

                                    default:
                                        break;
                                }
                            }
                            catch (Exception e)
                            {
                                // Add useful information to the exception
                                TextBoxLogWriteLine("There is a problem when creating the authorization policy for '{0}'.", AssetToProcess.Name, true);
                                TextBoxLogWriteLine(e);
                                ErrorCreationKey = true;
                            }

                        }
                        contentKeyAuthorizationPolicy.Update();
                    }

                    // Let's create the Asset Delivery Policy now
                    IAssetDeliveryPolicy DelPol = null;
                    string name = string.Format("AssetDeliveryPolicy {0} ({1})", form1.GetContentKeyType.ToString(), form1.GetAssetDeliveryProtocol.ToString());

                    try
                    {
                        DelPol = DynamicEncryption.CreateAssetDeliveryPolicyAES(AssetToProcess, contentKey, form1.GetAssetDeliveryProtocol, name, _context, aeslaurl);
                        TextBoxLogWriteLine("Created asset delivery policy {0} for asset {1}.", DelPol.AssetDeliveryPolicyType, AssetToProcess.Name);
                    }
                    catch (Exception e)
                    {
                        TextBoxLogWriteLine("There is a problem when creating the delivery policy for '{0}'.", AssetToProcess.Name, true);
                        TextBoxLogWriteLine(e);
                    }
                }
            }
        }
        private void DoDynamicEncryptionAndKeyDeliveryWithCENC(List<IAsset> SelectedAssets, AddDynamicEncryptionFrame1 form1, AddDynamicEncryptionFrame2_CENCKeyConfig form2_CENC, AddDynamicEncryptionFrame3_CENCDelivery form3_CENC, List<AddDynamicEncryptionFrame4> form4list, List<AddDynamicEncryptionFrame5_PlayReadyLicense> form5PlayReadyLicenseList, List<AddDynamicEncryptionFrame6_WidevineLicense> form6WidevineLicenseList, bool DisplayUI)
        {
            bool ErrorCreationKey = false;
            bool reusekey = false;
            bool firstkeycreation = true;
            IContentKey formerkey = null;

            if (!form2_CENC.ContentKeyRandomGeneration && (form2_CENC.KeyId != null))  // user want to manually enter the cryptography data and key if providedd 
            {
                // if the key already exists in the account (same key id), let's 
                formerkey = SelectedAssets.FirstOrDefault().GetMediaContext().ContentKeys.Where(c => c.Id == Constants.ContentKeyIdPrefix + form2_CENC.KeyId.ToString()).FirstOrDefault();
                if (formerkey != null)
                {
                    if (DisplayUI && MessageBox.Show("A Content key with the same Key Id exists already in the account.\nDo you want to try to replace it?\n(If not, the existing key will be used)", "Content key Id", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        // user wants to replace the key
                        try
                        {
                            formerkey.Delete();
                        }
                        catch (Exception e)
                        {
                            // Add useful information to the exception
                            TextBoxLogWriteLine("There is a problem when deleting the content key {0}.", formerkey.Id, true);
                            TextBoxLogWriteLine(e);
                            TextBoxLogWriteLine("The former key will be reused.", true);
                            reusekey = true;
                        }
                    }
                    else
                    {
                        reusekey = true;
                    }
                }
            }


            foreach (IAsset AssetToProcess in SelectedAssets)
            {
                if (AssetToProcess != null)
                {
                    IContentKey contentKey = null;
                    var contentkeys = AssetToProcess.ContentKeys.Where(c => c.ContentKeyType == form1.GetContentKeyType);
                    // special case, no dynamic encryption, goal is to setup key auth policy. CENC key is selected

                    if (contentkeys.Count() == 0) // no content key existing so we need to create one
                    {
                        ErrorCreationKey = false;

                        //    if ((form3_CENC.GetNumberOfAuthorizationPolicyOptionsPlayReady + form3_CENC.GetNumberOfAuthorizationPolicyOptionsWidevine) > 0 && form2_CENC.ContentKeyRandomGeneration)
                        //// Azure will deliver the PR or WV license and user wants to auto generate the key, so we can create a key with a random content key

                        if (!reusekey && ((form3_CENC.GetNumberOfAuthorizationPolicyOptionsPlayReady + form3_CENC.GetNumberOfAuthorizationPolicyOptionsWidevine) > 0 || form2_CENC.ContentKeyRandomGeneration))

                        // Azure will deliver the PR or WV license or user wants to auto generate the key, so we can create a key with a random content key
                        {
                            try
                            {
                                contentKey = DynamicEncryption.CreateCommonTypeContentKey(AssetToProcess, _context);
                            }
                            catch (Exception e)
                            {
                                // Add useful information to the exception
                                TextBoxLogWriteLine("There is a problem when creating the content key for '{0}'.", AssetToProcess.Name, true);
                                TextBoxLogWriteLine(e);
                                ErrorCreationKey = true;
                            }
                            if (!ErrorCreationKey)
                            {
                                TextBoxLogWriteLine("Created key {0} for asset '{1}'.", contentKey.Id, AssetToProcess.Name);
                            }

                        }
                        else // user wants to deliver with an external PlayReady or Widevine server or want to provide the key, so let's create the key based on what the user input
                        {
                            // if the key does not exist in the account (same key id), let's create it
                            if ((firstkeycreation && !reusekey) || form2_CENC.KeyId == null) // if we need to generate a new key id for each asset
                            {
                                if (form2_CENC.KeySeed != null) // seed has been given
                                {
                                    Guid keyid = (form2_CENC.KeyId == null) ? Guid.NewGuid() : (Guid)form2_CENC.KeyId;
                                    byte[] bytecontentkey = CommonEncryption.GeneratePlayReadyContentKey(Convert.FromBase64String(form2_CENC.KeySeed), keyid);
                                    try
                                    {
                                        contentKey = DynamicEncryption.CreateCommonTypeContentKey(AssetToProcess, _context, keyid, bytecontentkey);
                                    }
                                    catch (Exception e)
                                    {
                                        // Add useful information to the exception
                                        TextBoxLogWriteLine("There is a problem when creating the content key for '{0}'.", AssetToProcess.Name, true);
                                        TextBoxLogWriteLine(e);
                                        ErrorCreationKey = true;
                                    }
                                    if (!ErrorCreationKey)
                                    {
                                        TextBoxLogWriteLine("Created key {0} for the asset {1} ", contentKey.Id, AssetToProcess.Name);
                                    }
                                }
                                else // no seed given, so content key has been setup
                                {
                                    try
                                    {
                                        contentKey = DynamicEncryption.CreateCommonTypeContentKey(AssetToProcess, _context, (Guid)form2_CENC.KeyId, Convert.FromBase64String(form2_CENC.CENCContentKey));
                                    }
                                    catch (Exception e)
                                    {
                                        // Add useful information to the exception
                                        TextBoxLogWriteLine("There is a problem when creating the content key for asset '{0}'.", AssetToProcess.Name, true);
                                        TextBoxLogWriteLine(e);
                                        ErrorCreationKey = true;
                                    }
                                    if (!ErrorCreationKey)
                                    {
                                        TextBoxLogWriteLine("Created key {0} for asset '{1}'.", contentKey.Id, AssetToProcess.Name);
                                    }

                                }
                                formerkey = contentKey;
                                firstkeycreation = false;
                            }
                            else
                            {
                                contentKey = formerkey;
                                AssetToProcess.ContentKeys.Add(contentKey);
                                AssetToProcess.Update();
                                TextBoxLogWriteLine("Reusing key {0} for the asset {1} ", contentKey.Id, AssetToProcess.Name);
                            }
                        }
                    }
                    else if (false)//form1.PlayReadyPackaging form3_CENC.GetNumberOfAuthorizationPolicyOptionsPlayReady == 0 || form3_CENC.GetNumberOfAuthorizationPolicyOptionsWidevine == 0)
                                   // TO DO ? : if user wants to deliver license from external servers
                                   // user wants to deliver license with an external PlayReady and/or Widevine server but the key exists already !
                    {
                        TextBoxLogWriteLine("Warning for asset '{0}'. A CENC key already exists. You need to make sure that your external PlayReady or Widevine server can deliver the license for this asset.", AssetToProcess.Name, true);
                    }
                    else // let's use existing content key
                    {
                        contentKey = contentkeys.FirstOrDefault();
                        TextBoxLogWriteLine("Existing key '{0}' will be used for asset '{1}'.", contentKey.Id, AssetToProcess.Name);
                    }
                    if ((form3_CENC.GetNumberOfAuthorizationPolicyOptionsPlayReady + form3_CENC.GetNumberOfAuthorizationPolicyOptionsWidevine) > 0) // PlayReady/Widevine license and delivery from Azure Media Services
                    {
                        // let's create the Authorization Policy
                        IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = _context.
                                       ContentKeyAuthorizationPolicies.
                                       CreateAsync("Authorization Policy").Result;

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

                        foreach (var form4 in form4list)
                        { // for each option

                            string PlayReadyLicenseDeliveryConfig = null;
                            string WidevineLicenseDeliveryConfig = null;
                            bool ItIsAPlayReadyOption = form4list.IndexOf(form4) < form3_CENC.GetNumberOfAuthorizationPolicyOptionsPlayReady;

                            if (ItIsAPlayReadyOption)
                            { // user wants to define a PlayReady license for this option
                              // let's build the PlayReady license template

                                ErrorCreationKey = false;
                                try
                                {
                                    PlayReadyLicenseDeliveryConfig = form5PlayReadyLicenseList[form4list.IndexOf(form4)].GetLicenseTemplate;
                                }
                                catch (Exception e)
                                {
                                    // Add useful information to the exception
                                    TextBoxLogWriteLine("There is a problem when configuring the PlayReady license template.", true);
                                    TextBoxLogWriteLine(e);
                                    ErrorCreationKey = true;
                                }
                            }
                            else
                            { // user wants to define a Widevine license for this option

                                WidevineLicenseDeliveryConfig =
                                    form6WidevineLicenseList[form4list.IndexOf(form4) - form3_CENC.GetNumberOfAuthorizationPolicyOptionsPlayReady]
                                    .GetWidevineConfiguration(contentKey.GetKeyDeliveryUrl(ContentKeyDeliveryType.Widevine).ToString());
                            }

                            if (!ErrorCreationKey)
                            {
                                IContentKeyAuthorizationPolicyOption policyOption = null;
                                try
                                {
                                    switch (form4.GetKeyRestrictionType)
                                    {
                                        case ContentKeyRestrictionType.Open:
                                            if (ItIsAPlayReadyOption)
                                            {
                                                policyOption = DynamicEncryption.AddOpenAuthorizationPolicyOption(contentKey, ContentKeyDeliveryType.PlayReadyLicense, PlayReadyLicenseDeliveryConfig, _context);
                                                TextBoxLogWriteLine("Created PlayReady Open authorization policy for the asset '{0}' ", AssetToProcess.Name);
                                                contentKeyAuthorizationPolicy.Options.Add(policyOption);
                                            }
                                            else // widevine
                                            {
                                                policyOption = DynamicEncryption.AddOpenAuthorizationPolicyOption(contentKey, ContentKeyDeliveryType.Widevine, WidevineLicenseDeliveryConfig, _context);
                                                TextBoxLogWriteLine("Created Widevine Open authorization policy for the asset '{0}' ", AssetToProcess.Name);
                                                contentKeyAuthorizationPolicy.Options.Add(policyOption);
                                            }
                                            break;

                                        case ContentKeyRestrictionType.TokenRestricted:
                                            TokenVerificationKey mytokenverifkey = null;
                                            string OpenIdDoc = null;
                                            switch (form4.GetDetailedTokenType)
                                            {
                                                case ExplorerTokenType.SWT:
                                                case ExplorerTokenType.JWTSym:
                                                    mytokenverifkey = new SymmetricVerificationKey(Convert.FromBase64String(form4.SymmetricKey));
                                                    break;

                                                case ExplorerTokenType.JWTOpenID:
                                                    OpenIdDoc = form4.GetOpenIdDiscoveryDocument;
                                                    break;

                                                case ExplorerTokenType.JWTX509:
                                                    mytokenverifkey = new X509CertTokenVerificationKey(form4.GetX509Certificate);
                                                    break;
                                            }

                                            if (ItIsAPlayReadyOption)
                                            {
                                                policyOption = DynamicEncryption.AddTokenRestrictedAuthorizationPolicyCENC(ContentKeyDeliveryType.PlayReadyLicense, contentKey, form4.GetAudience, form4.GetIssuer, form4.GetTokenRequiredClaims, form4.AddContentKeyIdentifierClaim, form4.GetTokenType, form4.GetDetailedTokenType, mytokenverifkey, _context, PlayReadyLicenseDeliveryConfig, OpenIdDoc);
                                                TextBoxLogWriteLine("Created Token PlayReady authorization policy for the asset '{0}'.", AssetToProcess.Name);
                                            }
                                            else //widevine
                                            {
                                                policyOption = DynamicEncryption.AddTokenRestrictedAuthorizationPolicyCENC(ContentKeyDeliveryType.Widevine, contentKey, form4.GetAudience, form4.GetIssuer, form4.GetTokenRequiredClaims, form4.AddContentKeyIdentifierClaim, form4.GetTokenType, form4.GetDetailedTokenType, mytokenverifkey, _context, WidevineLicenseDeliveryConfig, OpenIdDoc);
                                                TextBoxLogWriteLine("Created Token Widevine authorization policy for the asset '{0}'", AssetToProcess.Name);
                                            }
                                            contentKeyAuthorizationPolicy.Options.Add(policyOption);


                                            if (form4.GetDetailedTokenType != ExplorerTokenType.JWTOpenID) // not possible to create a test token if OpenId is used
                                            {
                                                // let display a test token
                                                X509SigningCredentials signingcred = null;
                                                if (form4.GetDetailedTokenType == ExplorerTokenType.JWTX509)
                                                {
                                                    signingcred = new X509SigningCredentials(form4.GetX509Certificate);
                                                }

                                                _context = Program.ConnectAndGetNewContext(_credentials); // otherwise cache issues with multiple options
                                                DynamicEncryption.TokenResult testToken = DynamicEncryption.GetTestToken(AssetToProcess, _context, form1.GetContentKeyType, signingcred, policyOption.Id);
                                                TextBoxLogWriteLine("The authorization test token for option #{0} ({1} with Bearer) is:\n{2}", form4list.IndexOf(form4), form4.GetTokenType.ToString(), Constants.Bearer + testToken.TokenString);
                                                System.Windows.Forms.Clipboard.SetText(Constants.Bearer + testToken.TokenString);
                                            }
                                            break;

                                        default:
                                            break;
                                    }
                                }
                                catch (Exception e)
                                {
                                    // Add useful information to the exception
                                    TextBoxLogWriteLine("There is a problem when creating the authorization policy for '{0}'.", AssetToProcess.Name, true);
                                    TextBoxLogWriteLine(e);
                                    ErrorCreationKey = true;
                                }
                            }
                        }
                        contentKeyAuthorizationPolicy.Update();
                    }


                    // Let's create the Asset Delivery Policy now
                    if (form1.GetDeliveryPolicyType != AssetDeliveryPolicyType.None && form1.EnableDynEnc)
                    {
                        IAssetDeliveryPolicy DelPol = null;

                        var assetDeliveryProtocol = form1.GetAssetDeliveryProtocol;
                        if (!form1.PlayReadyPackaging && form1.WidevinePackaging)
                        {
                            assetDeliveryProtocol = AssetDeliveryProtocol.Dash;  // only DASH
                        }

                        string name = string.Format("AssetDeliveryPolicy {0} ({1})", form1.GetContentKeyType.ToString(), assetDeliveryProtocol.ToString());
                        ErrorCreationKey = false;

                        try
                        {
                            DelPol = DynamicEncryption.CreateAssetDeliveryPolicyCENC(
                                AssetToProcess,
                                contentKey,
                                form1,
                                name,
                                _context,
                                playreadyAcquisitionUrl: form3_CENC.GetNumberOfAuthorizationPolicyOptionsPlayReady > 0 ? null : form3_CENC.PlayReadyLAurl,
                                playreadyEncodeLAURLForSilverlight: form3_CENC.GetNumberOfAuthorizationPolicyOptionsPlayReady > 0 ? false : form3_CENC.PlayReadyLAurlEncodeForSL,
                                widevineAcquisitionUrl: form3_CENC.GetNumberOfAuthorizationPolicyOptionsWidevine > 0 ? null : form3_CENC.WidevineLAurl
                                );

                            TextBoxLogWriteLine("Created asset delivery policy '{0}' for asset '{1}'.", DelPol.AssetDeliveryPolicyType, AssetToProcess.Name);
                        }
                        catch (Exception e)
                        {
                            TextBoxLogWriteLine("There is a problem when creating the delivery policy for '{0}'.", AssetToProcess.Name, true);
                            TextBoxLogWriteLine(e);
                            ErrorCreationKey = true;
                        }
                    }
                }
            }
        }
        // Get the access token via straight http post request doing client credential flow
        private async Task<String> GetAppOnlyAccessTokenWithHttpRequest(string resource, string tenantId)
        {
            /**
             * use the tenant specific endpoint for requesting the app-only access token
             */
            string tokenIssueEndpoint = appConfig.TokenIssueingUri.Replace("common", tenantId);

            /**
             * sign the assertion with the private key
             */
            string certfile = Server.MapPath(appConfig.ClientCertificatePfx);
            X509Certificate2 cert = new X509Certificate2(
                certfile,
                appConfig.ClientCertificatePfxPassword,
                X509KeyStorageFlags.MachineKeySet);

            /**
             * Example building assertion using Json Tokenhandler. 
             * Sort of cheating, but just if someone wonders ... there are always more ways to do something :-)
             */
            Dictionary<string, string> claims = new Dictionary<string, string>()
            {
                { "sub", appConfig.ClientId },
                { "jti", Guid.NewGuid().ToString() },
            };

            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            X509SigningCredentials signingCredentials = new X509SigningCredentials(cert, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);

            JwtSecurityToken selfSignedToken = new JwtSecurityToken(
                appConfig.ClientId,
                tokenIssueEndpoint,
                claims.Select(c => new Claim(c.Key, c.Value)),
                DateTime.UtcNow, 
                DateTime.UtcNow.Add(TimeSpan.FromMinutes(15)),
                signingCredentials);

            string signedAssertion = tokenHandler.WriteToken(selfSignedToken);

            //---- End example with Json Tokenhandler... now to the fun part doing it all ourselves ...

            /**
              * Example building assertion from scratch with Crypto APIs
            */
            JObject clientAssertion = new JObject();
            clientAssertion.Add("aud", tokenIssueEndpoint);
            clientAssertion.Add("iss", appConfig.ClientId);
            clientAssertion.Add("sub", appConfig.ClientId);
            clientAssertion.Add("jti", Guid.NewGuid().ToString());
            clientAssertion.Add("nbf", WebConvert.EpocTime(DateTime.UtcNow + TimeSpan.FromMinutes(-5)));
            clientAssertion.Add("exp", WebConvert.EpocTime(DateTime.UtcNow + TimeSpan.FromMinutes(15)));

            string assertionPayload = clientAssertion.ToString(Newtonsoft.Json.Formatting.None);

            X509AsymmetricSecurityKey x509Key = new X509AsymmetricSecurityKey(cert);
            RSACryptoServiceProvider rsa = x509Key.GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha256Signature, true) as RSACryptoServiceProvider;
            RSACryptoServiceProvider newRsa = GetCryptoProviderForSha256(rsa);
            SHA256Cng sha = new SHA256Cng();

            JObject header = new JObject(new JProperty("alg", "RS256"));
            string thumbprint = WebConvert.Base64UrlEncoded(WebConvert.HexStringToBytes(cert.Thumbprint));
            header.Add(new JProperty("x5t", thumbprint));

            string encodedHeader = WebConvert.Base64UrlEncoded(header.ToString());
            string encodedPayload = WebConvert.Base64UrlEncoded(assertionPayload);

            string signingInput = String.Concat(encodedHeader, ".", encodedPayload);

            byte[] signature = newRsa.SignData(Encoding.UTF8.GetBytes(signingInput), sha);
  
            signedAssertion = string.Format("{0}.{1}.{2}",
                encodedHeader,
                encodedPayload,
                WebConvert.Base64UrlEncoded(signature));

            /**
             * build the request payload
             */
            FormUrlEncodedContent tokenRequestForm;
            tokenRequestForm = new FormUrlEncodedContent(
                new[] { 
                new KeyValuePair<string,string>("resource", appConfig.ExchangeResourceUri),
                new KeyValuePair<string,string>("client_id", appConfig.ClientId),
                new KeyValuePair<string,string>("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),
                new KeyValuePair<string,string>("client_assertion", signedAssertion),
                new KeyValuePair<string,string>("grant_type","client_credentials"),
                }
                );

            /*
             * Do the web request
             */
            HttpClient client = new HttpClient();

            Task<string> requestString = tokenRequestForm.ReadAsStringAsync();
            StringContent requestContent = new StringContent(requestString.Result);
            requestContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            requestContent.Headers.Add("client-request-id", System.Guid.NewGuid().ToString());
            requestContent.Headers.Add("return-client-request-id", "true");
            requestContent.Headers.Add("UserAgent", "MatthiasLeibmannsAppOnlyAppSampleBeta/0.1");

            HttpResponseMessage response = client.PostAsync(tokenIssueEndpoint, requestContent).Result;
            JObject jsonResponse = JObject.Parse(response.Content.ReadAsStringAsync().Result);
            JsonSerializer jsonSerializer = new JsonSerializer();

            if(response.IsSuccessStatusCode == true)
            { 
                AADClientCredentialSuccessResponse s = (AADClientCredentialSuccessResponse)jsonSerializer.Deserialize(new JTokenReader(jsonResponse), typeof(AADClientCredentialSuccessResponse));
                return s.access_token;
            }

            AADClientCredentialErrorResponse e = (AADClientCredentialErrorResponse)jsonSerializer.Deserialize(new JTokenReader(jsonResponse), typeof(AADClientCredentialErrorResponse));
            throw new Exception(e.error_description);
        }
        protected override Scope GetScope(IClaimsPrincipal principal, RequestSecurityToken request)
        {
            // Create the scope using the request AppliesTo address, the STS signing certificate and the encryptingCredentials for the RP.
            if (request.AppliesTo == null || request.AppliesTo.Uri == null)
            {
                throw new InvalidRequestException("Cannot determine the AppliesTo address from the RequestSecurityToken.");
            }

            ValidateIssuer(request);

            ValidateAudienceRestriction(principal, request);

            ValidateAppliesTo(request.AppliesTo);

            X509Certificate2 signingCert = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine,
                WebConfigurationManager.AppSettings["SigningCertificateName"]);

            SecurityKeyIdentifier signingSki = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] { 
                new X509SecurityToken(signingCert).CreateKeyIdentifierClause<X509RawDataKeyIdentifierClause>() });

            X509SigningCredentials signingCredentialss = new X509SigningCredentials(signingCert, signingSki);

            Scope scope = new Scope(request.AppliesTo.Uri.OriginalString, signingCredentialss);

            // The assertion is not encrypted
            scope.TokenEncryptionRequired = false;

            return scope;
        }
Ejemplo n.º 22
0
        public StsConfiguration(String host)
        {
            SecurityTokenService = typeof(Sts);
            // this.DefaultTokenType = "http://schemas.microsoft.com/ws/2006/05/identitymodel/tokens/Rsa";
            // this.SecurityTokenHandlers.AddOrReplace(new SimpleWebTokenHandler());

            settings = SecurityTokenServicesSection.Current.GetConfiguration(host);

            // Configure token issuer
            TokenIssuerName = settings.IssuerName;

            // Configure signing and encrypting certificates
            X509Store store = new X509Store(settings.StoreName, settings.StoreLocation);
            try
            {
                store.Open(OpenFlags.ReadOnly);

                SigningCredentials = new X509SigningCredentials(
                    store.FindExactlyOne(settings.SigningCertificateName));

                if (false == String.IsNullOrEmpty(settings.EncryptingCertificateName))
                {
                    EncryptingCredentials = new X509EncryptingCredentials(
                        store.FindExactlyOne(settings.EncryptingCertificateName));
                }
            }
            finally
            {
                store.Close();
            }

            // Load standard claims
            foreach (FieldInfo claim in typeof(ClaimTypes).GetFields())
            {
                standardClaims.Add(claim.Name, claim.GetValue(null) as String);
            }
        }
        public virtual async Task<string> CreateSecurityTokenAsync(Token token)
        {
            if (token.Type == Constants.TokenTypes.AccessToken)
            {
                if (token.Client.AccessTokenType == AccessTokenType.JWT)
                {
                    return CreateJsonWebToken(
                        token,
                        new X509SigningCredentials(_settings.GetSigningCertificate()));
                }
                else
                {
                    var handle = Guid.NewGuid().ToString("N");
                    await _tokenHandles.StoreAsync(handle, token);

                    return handle;
                }
            }

            if (token.Type == Constants.TokenTypes.IdentityToken)
            {
                SigningCredentials credentials;
                if (token.Client.IdentityTokenSigningKeyType == SigningKeyTypes.ClientSecret)
                {
                    credentials = new HmacSigningCredentials(token.Client.ClientSecret);
                }
                else
                {
                    credentials = new X509SigningCredentials(_settings.GetSigningCertificate());
                }

                return CreateJsonWebToken(token, credentials);
            }

            throw new InvalidOperationException("Invalid token type.");
        }
        private void DoDynamicEncryptionWithAES(List<IAsset> SelectedAssets, AddDynamicEncryptionFrame1 form1, AddDynamicEncryptionFrame2_AESKeyConfig form2, List<AddDynamicEncryptionFrame3> form3list)
        {
            bool Error = false;
            string aeskey = string.Empty;
            if (!form2.ContentKeyRandomGeneration)
            {
                aeskey = form2.AESContentKey;
            }

            foreach (IAsset AssetToProcess in SelectedAssets)
            {

                if (AssetToProcess != null)
                {
                    IContentKey contentKey = null;

                    var contentkeys = AssetToProcess.ContentKeys.Where(c => c.ContentKeyType == form1.GetContentKeyType);
                    if (contentkeys.Count() == 0) // no content key existing so we need to create one
                    {
                        Error = false;
                        try
                        {
                            if ((!form2.ContentKeyRandomGeneration) && !string.IsNullOrEmpty(aeskey)) // user has to provide the key
                            {
                                contentKey = DynamicEncryption.CreateEnvelopeTypeContentKey(AssetToProcess, Convert.FromBase64String(aeskey));
                            }
                            else
                            {
                                contentKey = DynamicEncryption.CreateEnvelopeTypeContentKey(AssetToProcess);
                            }
                        }
                        catch (Exception e)
                        {
                            // Add useful information to the exception
                            TextBoxLogWriteLine("There is a problem when creating the content key for '{0}'.", AssetToProcess.Name, true);
                            TextBoxLogWriteLine(e);
                            Error = true;
                        }
                        if (!Error)
                        {
                            TextBoxLogWriteLine("Created key {0} for the asset {1} ", contentKey.Id, AssetToProcess.Name);
                        }

                    }

                    else // let's use existing content key
                    {
                        contentKey = contentkeys.FirstOrDefault();
                        TextBoxLogWriteLine("Existing key {0} will be used for asset {1}.", contentKey.Id, AssetToProcess.Name);
                    }


                    // let's create the Authorization Policy
                    IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = _context.
                                   ContentKeyAuthorizationPolicies.
                                   CreateAsync("My Authorization Policy").Result;

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


                    foreach (var form3 in form3list)
                    {
                        IContentKeyAuthorizationPolicyOption policyOption = null;
                        Error = false;
                        try
                        {
                            switch (form3.GetKeyRestrictionType)
                            {
                                case ContentKeyRestrictionType.Open:

                                    policyOption = DynamicEncryption.AddOpenAuthorizationPolicyOption(contentKey, ContentKeyDeliveryType.BaselineHttp, null, _context);
                                    TextBoxLogWriteLine("Created Open authorization policy for the asset {0} ", contentKey.Id, AssetToProcess.Name);
                                    contentKeyAuthorizationPolicy.Options.Add(policyOption);
                                    break;

                                case ContentKeyRestrictionType.TokenRestricted:
                                    TokenVerificationKey mytokenverifkey = null;
                                    string OpenIdDoc = null;
                                    switch (form3.GetDetailedTokenType)
                                    {
                                        case ExplorerTokenType.SWT:
                                        case ExplorerTokenType.JWTSym:
                                            mytokenverifkey = new SymmetricVerificationKey(Convert.FromBase64String(form3.SymmetricKey));
                                            break;

                                        case ExplorerTokenType.JWTOpenID:
                                            OpenIdDoc = form3.GetOpenIdDiscoveryDocument;
                                            break;

                                        case ExplorerTokenType.JWTX509:
                                            mytokenverifkey = new X509CertTokenVerificationKey(form3.GetX509Certificate);
                                            break;
                                    }

                                    policyOption = DynamicEncryption.AddTokenRestrictedAuthorizationPolicyAES(contentKey, form3.GetAudience, form3.GetIssuer, form3.GetTokenRequiredClaims, form3.AddContentKeyIdentifierClaim, form3.GetTokenType, form3.GetDetailedTokenType, mytokenverifkey, _context, OpenIdDoc);
                                    TextBoxLogWriteLine("Created Token AES authorization policy for the asset {0} ", contentKey.Id, AssetToProcess.Name);
                                    contentKeyAuthorizationPolicy.Options.Add(policyOption);

                                    if (form3.GetDetailedTokenType != ExplorerTokenType.JWTOpenID) // not possible to create a test token if OpenId is used
                                    {
                                        // let display a test token
                                        X509SigningCredentials signingcred = null;
                                        if (form3.GetDetailedTokenType == ExplorerTokenType.JWTX509)
                                        {
                                            signingcred = new X509SigningCredentials(form3.GetX509Certificate);
                                        }

                                        _context = Program.ConnectAndGetNewContext(_credentials); // otherwise cache issues with multiple options
                                        DynamicEncryption.TokenResult testToken = DynamicEncryption.GetTestToken(AssetToProcess, _context, form1.GetContentKeyType, signingcred, policyOption.Id);
                                        TextBoxLogWriteLine("The authorization test token for option #{0} ({1} with Bearer) is:\n{2}", form3list.IndexOf(form3), form3.GetTokenType.ToString(), Constants.Bearer + testToken.TokenString);
                                        System.Windows.Forms.Clipboard.SetText(Constants.Bearer + testToken.TokenString);

                                    }
                                    break;

                                default:
                                    break;
                            }
                        }
                        catch (Exception e)
                        {
                            // Add useful information to the exception
                            TextBoxLogWriteLine("There is a problem when creating the authorization policy for '{0}'.", AssetToProcess.Name, true);
                            TextBoxLogWriteLine(e);
                            Error = true;
                        }

                    }
                    contentKeyAuthorizationPolicy.Update();

                    // Let's create the Asset Delivery Policy now
                    IAssetDeliveryPolicy DelPol = null;
                    string name = string.Format("AssetDeliveryPolicy {0} ({1})", form1.GetContentKeyType.ToString(), form1.GetAssetDeliveryProtocol.ToString());

                    try
                    {
                        DelPol = DynamicEncryption.CreateAssetDeliveryPolicyAES(AssetToProcess, contentKey, form1.GetAssetDeliveryProtocol, name, _context);
                        TextBoxLogWriteLine("Created asset delivery policy {0} for asset {1}.", DelPol.AssetDeliveryPolicyType, AssetToProcess.Name);
                    }
                    catch (Exception e)
                    {
                        TextBoxLogWriteLine("There is a problem when creating the delivery policy for '{0}'.", AssetToProcess.Name, true);
                        TextBoxLogWriteLine(e);
                    }
                }
            }
        }