Esempio n. 1
0
        /// <summary>
        /// Generates an encrypted assertion and writes it to disk.
        /// </summary>
        public static void GenerateEncryptedAssertion()
        {
            var cert      = Certificates.InMemoryResourceUtility.GetInMemoryCertificate("sts_dev_certificate.pfx", "test1234");
            var assertion = AssertionUtil.GetTestAssertion();

            // Create an EncryptedData instance to hold the results of the encryption.o
            var encryptedData = new EncryptedData
            {
                Type             = EncryptedXml.XmlEncElementUrl,
                EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url)
            };

            // Create a symmetric key.
            var aes = new RijndaelManaged {
                KeySize = 256
            };

            aes.GenerateKey();

            // Encrypt the assertion and add it to the encryptedData instance.
            var encryptedXml     = new EncryptedXml();
            var encryptedElement = encryptedXml.EncryptData(assertion.DocumentElement, aes, false);

            encryptedData.CipherData.CipherValue = encryptedElement;

            // Add an encrypted version of the key used.
            encryptedData.KeyInfo = new KeyInfo();

            var encryptedKey = new EncryptedKey();

            // Use this certificate to encrypt the key.
            var publicKeyRsa = cert.PublicKey.Key as RSA;

            Assert.True(publicKeyRsa != null, "Public key of certificate was not an RSA key. Modify test.");
            encryptedKey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);
            encryptedKey.CipherData       = new CipherData(EncryptedXml.EncryptKey(aes.Key, publicKeyRsa, false));

            encryptedData.KeyInfo.AddClause(new KeyInfoEncryptedKey(encryptedKey));

            // Create the resulting Xml-document to hook into.
            var encryptedAssertion = new EncryptedAssertion
            {
                EncryptedData = new Schema.XEnc.EncryptedData(),
                EncryptedKey  = new Schema.XEnc.EncryptedKey[1]
            };

            encryptedAssertion.EncryptedKey[0] = new Schema.XEnc.EncryptedKey();

            var result = Serialization.Serialize(encryptedAssertion);

            var encryptedDataElement = GetElement(Schema.XEnc.EncryptedData.ElementName, Saml20Constants.Xenc, result);

            EncryptedXml.ReplaceElement(encryptedDataElement, encryptedData, false);

            // At this point, result can be output to text
        }
Esempio n. 2
0
        public void GenerateEncryptedAssertion_01()
        {
            XmlDocument assertion = AssertionUtil.GetTestAssertion_01();

            // Create an EncryptedData instance to hold the results of the encryption.o
            EncryptedData encryptedData = new EncryptedData();

            encryptedData.Type             = EncryptedXml.XmlEncElementUrl;
            encryptedData.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);

            // Create a symmetric key.
            RijndaelManaged aes = new RijndaelManaged();

            aes.KeySize = 256;
            aes.GenerateKey();

            // Encrypt the assertion and add it to the encryptedData instance.
            EncryptedXml encryptedXml = new EncryptedXml();

            byte[] encryptedElement = encryptedXml.EncryptData(assertion.DocumentElement, aes, false);
            encryptedData.CipherData.CipherValue = encryptedElement;

            // Add an encrypted version of the key used.
            encryptedData.KeyInfo = new KeyInfo();

            EncryptedKey encryptedKey = new EncryptedKey();

            // Use this certificate to encrypt the key.
            X509Certificate2 cert = new X509Certificate2(@"Saml20\Certificates\sts_dev_certificate.pfx", "test1234");
            RSA publicKeyRSA      = cert.PublicKey.Key as RSA;

            Assert.IsNotNull(publicKeyRSA, "Public key of certificate was not an RSA key. Modify test.");
            encryptedKey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);
            encryptedKey.CipherData       = new CipherData(EncryptedXml.EncryptKey(aes.Key, publicKeyRSA, false));


            encryptedData.KeyInfo.AddClause(new KeyInfoEncryptedKey(encryptedKey));

            // Create the resulting Xml-document to hook into.
            EncryptedAssertion encryptedAssertion = new EncryptedAssertion();

            encryptedAssertion.encryptedData   = new saml20.Schema.XEnc.EncryptedData();
            encryptedAssertion.encryptedKey    = new saml20.Schema.XEnc.EncryptedKey[1];
            encryptedAssertion.encryptedKey[0] = new saml20.Schema.XEnc.EncryptedKey();

            XmlDocument result;

            result = Serialization.Serialize(encryptedAssertion);

            XmlElement encryptedDataElement = GetElement(dk.nita.saml20.Schema.XEnc.EncryptedData.ELEMENT_NAME, Saml20Constants.XENC, result);

            EncryptedXml.ReplaceElement(encryptedDataElement, encryptedData, false);
        }
        /// <summary>
        /// Encrypts the Assertion in the assertion property and creates an <code>EncryptedAssertion</code> element
        /// that can be retrieved using the <code>GetXml</code> method.
        /// </summary>
        public void Encrypt()
        {
            if (_transportKey == null)
            {
                throw new InvalidOperationException("The \"TransportKey\" property is required to encrypt the assertion.");
            }

            if (_assertion == null)
            {
                throw new InvalidOperationException("The \"Assertion\" property is required for this operation.");
            }

            EncryptedData encryptedData = new EncryptedData();

            encryptedData.Type = EncryptedXml.XmlEncElementUrl;

            encryptedData.EncryptionMethod = new EncryptionMethod(_sessionKeyAlgorithm);

            // Encrypt the assertion and add it to the encryptedData instance.
            EncryptedXml encryptedXml = new EncryptedXml();

            byte[] encryptedElement = encryptedXml.EncryptData(_assertion.DocumentElement, SessionKey, false);
            encryptedData.CipherData.CipherValue = encryptedElement;

            // Add an encrypted version of the key used.
            encryptedData.KeyInfo = new KeyInfo();

            EncryptedKey encryptedKey = new EncryptedKey();

            encryptedKey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);
            encryptedKey.CipherData       = new CipherData(EncryptedXml.EncryptKey(SessionKey.Key, TransportKey, false));
            encryptedData.KeyInfo.AddClause(new KeyInfoEncryptedKey(encryptedKey));

            // Create an empty EncryptedAssertion to hook into.
            var encryptedAssertion = new EncryptedAssertion();

            encryptedAssertion.encryptedData = new SfwEncryptedData();

            XmlDocument result = new XmlDocument();

            result.XmlResolver = null;
            result.LoadXml(Serialization.SerializeToXmlString(encryptedAssertion));



            XmlElement encryptedDataElement = GetElement(SfwEncryptedData.ELEMENT_NAME, Saml20Constants.XENC, result.DocumentElement);

            EncryptedXml.ReplaceElement(encryptedDataElement, encryptedData, false);

            _encryptedAssertion = result;
        }
Esempio n. 4
0
        /// <summary>
        /// Encrypts the Assertion in the assertion property and creates an <code>EncryptedAssertion</code> element
        /// that can be retrieved using the <code>GetXml</code> method.
        /// </summary>
        public void Encrypt()
        {
            if (TransportKey == null)
            {
                throw new InvalidOperationException("The \"TransportKey\" property is required to encrypt the assertion.");
            }

            if (Assertion == null)
            {
                throw new InvalidOperationException("The \"Assertion\" property is required for this operation.");
            }

            var encryptedData = new EncryptedData
            {
                Type             = EncryptedXml.XmlEncElementUrl,
                EncryptionMethod = new EncryptionMethod(_sessionKeyAlgorithm)
            };

            // Encrypt the assertion and add it to the encryptedData instance.
            var encryptedXml     = new EncryptedXml();
            var encryptedElement = encryptedXml.EncryptData(Assertion.DocumentElement, SessionKey, false);

            encryptedData.CipherData.CipherValue = encryptedElement;

            // Add an encrypted version of the key used.
            encryptedData.KeyInfo = new KeyInfo();

            var encryptedKey = new EncryptedKey
            {
                EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url),
                CipherData       = new CipherData(EncryptedXml.EncryptKey(SessionKey.Key, TransportKey, false))
            };

            encryptedData.KeyInfo.AddClause(new KeyInfoEncryptedKey(encryptedKey));

            // Create an empty EncryptedAssertion to hook into.
            var encryptedAssertion = new EncryptedAssertion {
                EncryptedData = new Schema.XEnc.EncryptedData()
            };

            var result = new XmlDocument();

            result.LoadXml(Serialization.SerializeToXmlString(encryptedAssertion));

            var encryptedDataElement = GetElement(Schema.XEnc.EncryptedData.ElementName, Saml20Constants.Xenc, result.DocumentElement);

            EncryptedXml.ReplaceElement(encryptedDataElement, encryptedData, false);

            _encryptedAssertion = result;
        }
Esempio n. 5
0
        private static XmlElement DecryptAssertion(XmlElement xmlElement)
        {
            Console.Error.WriteLine("Decrypting SAML assertion");

            EncryptedAssertion encryptedAssertion = new EncryptedAssertion(xmlElement);

            EncryptionMethod encryptionMethod = null;

            if (!String.IsNullOrEmpty(algorithm)) {
                encryptionMethod = new EncryptionMethod(algorithm);
            }

            return encryptedAssertion.DecryptToXml(x509Certificate.PrivateKey, null, encryptionMethod);
        }
Esempio n. 6
0
        private static XmlElement DecryptAssertion(XmlElement xmlElement)
        {
            Console.Error.WriteLine("Decrypting SAML assertion");

            EncryptedAssertion encryptedAssertion = new EncryptedAssertion(xmlElement);

            EncryptionMethod encryptionMethod = null;

            if (!String.IsNullOrEmpty(algorithm))
            {
                encryptionMethod = new EncryptionMethod(algorithm);
            }

            return(encryptedAssertion.DecryptToXml(x509Certificate.PrivateKey, null, encryptionMethod));
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try
            {
                #region Receive SAML Response

                // Create a SAML response from the HTTP request.
                ComponentPro.Saml2.Response samlResponse = ComponentPro.Saml2.Response.Create(Request);

                // Is it signed?
                if (samlResponse.IsSigned())
                {
                    // Loaded the previously loaded certificate.
                    X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.CertKeyName];

                    // Validate the SAML response with the certificate.
                    if (!samlResponse.Validate(x509Certificate))
                    {
                        throw new ApplicationException("SAML response signature is not valid.");
                    }
                }

                #endregion

                #region Process the response

                // Success?
                if (!samlResponse.IsSuccess())
                {
                    throw new ApplicationException("SAML response is not success");
                }

                Assertion samlAssertion;

                // Define ENCRYPTEDSAML preprocessor flag if you wish to decrypt the SAML response.
#if ENCRYPTEDSAML
                if (samlResponse.GetEncryptedAssertions().Count > 0)
                {
                    EncryptedAssertion encryptedAssertion = samlResponse.GetEncryptedAssertions()[0];

                    // Load the private key.
                    // Consider caching the loaded key in production environment for better performance.
                    X509Certificate2 decryptionKey = new X509Certificate2(Path.Combine(HttpRuntime.AppDomainAppPath, "EncryptionKey.pfx"), "password");

                    // Decrypt the encrypted assertion.
                    samlAssertion = encryptedAssertion.Decrypt(decryptionKey.PrivateKey, null);
                }
                else
                {
                    throw new ApplicationException("No encrypted assertions found in the SAML response");
                }
#else
                // Get the asserted identity.
                if (samlResponse.GetAssertions().Count > 0)
                {
                    samlAssertion = samlResponse.GetAssertions()[0];
                }
                else
                {
                    throw new ApplicationException("No assertions found in the SAML response");
                }
#endif

                // Get the subject name identifier.
                string userName;

                if (samlAssertion.Subject.NameId != null)
                {
                    userName = samlAssertion.Subject.NameId.NameIdentifier;
                }
                else
                {
                    throw new ApplicationException("Name identifier not found in subject");
                }

                #region Extract Custom Attributes

                // If you need to add custom attributes, uncomment the following code
                //if (samlAssertion.AttributeStatements.Count > 0)
                //{
                //    foreach (AttributeStatement attributeStatement in samlAssertion.AttributeStatements)
                //    {
                //        // If you need to decrypt encrypted attributes, refer to this topic: http://www.samlcomponent.net/encrypting-and-decrypting-saml-response-xml
                //        foreach (ComponentPro.Saml2.Attribute attribute in attributeStatement.Attributes)
                //        {
                //            // Process your custom attribute here.
                //            // ...
                //        }
                //    }
                //}

                #endregion

                // Set authentication cookie.
                FormsAuthentication.SetAuthCookie(userName, false);

                // Redirect to the requested URL.
                Response.Redirect(samlResponse.RelayState, false);

                #endregion
            }

            catch (Exception exception)
            {
                Trace.Write("ServiceProvider", "An Error occurred", exception);
            }
        }
Esempio n. 8
0
        private static XmlElement CreateSamlResponse(string assertionConsumerServiceUrl, List <SAMLAttribute> attributes, string requestId = null, bool signAssertion = false, bool signResponse = false, bool encryptAssertion = false)
        {
            var samlResponse = new SAMLResponse {
                Destination = assertionConsumerServiceUrl
            };
            var issuer = new Issuer(SAMLConfiguration.Current.IdentityProviderConfiguration.Name);
            var issuerX509CertificateFilePath = Path.Combine(HttpRuntime.AppDomainAppPath, SAMLConfiguration.Current.IdentityProviderConfiguration.CertificateFile);
            var issuerX509Certificate         = new X509Certificate2(issuerX509CertificateFilePath, SAMLConfiguration.Current.IdentityProviderConfiguration.CertificatePassword);
            var partner       = SessionHelper.Get <string>(PartnerSpSessionKey) ?? SAMLConfiguration.Current.ServiceProviderConfiguration.Name;
            var partnerConfig = SAMLConfiguration.Current.PartnerServiceProviderConfigurations[partner];
            var partnerX509CertificateFilePath = string.Empty;
            var partnerX509Certificate         = null as X509Certificate2;

            if (partnerConfig != null)
            {
                partnerX509CertificateFilePath = Path.Combine(HttpRuntime.AppDomainAppPath, partnerConfig.CertificateFile);
                partnerX509Certificate         = new X509Certificate2(partnerX509CertificateFilePath);
                signAssertion    = partnerConfig.SignAssertion;
                signResponse     = partnerConfig.SignSAMLResponse;
                encryptAssertion = partnerConfig.EncryptAssertion;
            }

            samlResponse.Issuer       = issuer;
            samlResponse.Status       = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null);
            samlResponse.IssueInstant = DateTime.Now;
            samlResponse.InResponseTo = requestId;

            var samlAssertion = new SAMLAssertion {
                Issuer = issuer, IssueInstant = samlResponse.IssueInstant
            };

            var profileId               = attributes.Where(a => a.Name == PortalClaimTypes.ProfileId).Select(a => a.Values[0].ToString()).FirstOrDefault();
            var subject                 = new Subject(new NameID(profileId));
            var subjectConfirmation     = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer);
            var subjectConfirmationData = new SubjectConfirmationData {
                Recipient = assertionConsumerServiceUrl
            };

            subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
            subject.SubjectConfirmations.Add(subjectConfirmation);
            samlAssertion.Subject = subject;

            var conditions          = new Conditions(DateTime.Now, DateTime.Now.AddDays(1));
            var audienceRestriction = new AudienceRestriction();

            audienceRestriction.Audiences.Add(new Audience(partner));
            conditions.ConditionsList.Add(audienceRestriction);
            samlAssertion.Conditions = conditions;

            var authnStatement = new AuthnStatement {
                AuthnContext = new AuthnContext(), AuthnInstant = samlResponse.IssueInstant
            };

            authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.X509);
            samlAssertion.Statements.Add(authnStatement);

            attributes.ForEach(a =>
            {
                var attributeStatement = new AttributeStatement();

                attributeStatement.Attributes.Add(a);
                samlAssertion.Statements.Add(attributeStatement);
            });

            var samlAssertionXml = samlAssertion.ToXml();

            if (signAssertion)
            {
                SAMLAssertionSignature.Generate(samlAssertionXml, issuerX509Certificate.PrivateKey, issuerX509Certificate);
            }

            if (encryptAssertion)
            {
                var encryptedAssertion = new EncryptedAssertion(samlAssertionXml, partnerX509Certificate);

                samlResponse.Assertions.Add(encryptedAssertion.ToXml());
            }
            else
            {
                samlResponse.Assertions.Add(samlAssertionXml);
            }

            var samlResponseXml = samlResponse.ToXml();

            if (signResponse)
            {
                SAMLMessageSignature.Generate(samlResponseXml, issuerX509Certificate.PrivateKey, issuerX509Certificate);
            }

            return(samlResponseXml);
        }
Esempio n. 9
0
        private void CreateAssertionResponse(User user)
        {
            string entityId = request.Issuer.Value;
            Saml20MetadataDocument metadataDocument = IDPConfig.GetServiceProviderMetadata(entityId);
            IDPEndPointElement     endpoint         =
                metadataDocument.AssertionConsumerServiceEndpoints().Find(delegate(IDPEndPointElement e) { return(e.Binding == SAMLBinding.POST); });

            if (endpoint == null)
            {
                Context.Response.Write(string.Format("'{0}' does not have a SSO endpoint that supports the POST binding.", entityId));
                Context.Response.End();
                return;
            }

            UserSessionsHandler.AddLoggedInSession(entityId);

            Response response = new Response();

            response.Destination             = endpoint.Url;
            response.InResponseTo            = request.ID;
            response.Status                  = new Status();
            response.Status.StatusCode       = new StatusCode();
            response.Status.StatusCode.Value = Saml20Constants.StatusCodes.Success;

            var       nameIdFormat = metadataDocument.Entity.Items.OfType <SPSSODescriptor>().SingleOrDefault()?.NameIDFormat.SingleOrDefault() ?? Saml20Constants.NameIdentifierFormats.Persistent;
            Assertion assertion    = CreateAssertion(user, entityId, nameIdFormat);

            var signatureProvider = SignatureProviderFactory.CreateFromShaHashingAlgorithmName(ShaHashingAlgorithm.SHA256);
            EncryptedAssertion encryptedAssertion = null;

            var keyDescriptors = metadataDocument.Keys.Where(x => x.use == KeyTypes.encryption);

            if (keyDescriptors.Any())
            {
                foreach (KeyDescriptor keyDescriptor in keyDescriptors)
                {
                    KeyInfo ki = (KeyInfo)keyDescriptor.KeyInfo;

                    foreach (KeyInfoClause clause in ki)
                    {
                        if (clause is KeyInfoX509Data)
                        {
                            X509Certificate2 cert = XmlSignatureUtils.GetCertificateFromKeyInfo((KeyInfoX509Data)clause);

                            var    spec = new DefaultCertificateSpecification();
                            string error;
                            if (spec.IsSatisfiedBy(cert, out error))
                            {
                                AsymmetricAlgorithm key = XmlSignatureUtils.ExtractKey(clause);
                                AssertionEncryptionUtility.AssertionEncryptionUtility encryptedAssertionUtil = new AssertionEncryptionUtility.AssertionEncryptionUtility((RSA)key, assertion);

                                // Sign the assertion inside the response message.
                                signatureProvider.SignAssertion(encryptedAssertionUtil.Assertion, assertion.ID, IDPConfig.IDPCertificate);

                                encryptedAssertionUtil.Encrypt();
                                encryptedAssertion = Serialization.DeserializeFromXmlString <EncryptedAssertion>(encryptedAssertionUtil.EncryptedAssertion.OuterXml);
                                break;
                            }
                        }
                    }
                    if (encryptedAssertion != null)
                    {
                        break;
                    }
                }

                if (encryptedAssertion == null)
                {
                    throw new Exception("Could not encrypt. No valid certificates found.");
                }
            }

            if (encryptedAssertion != null)
            {
                response.Items = new object[] { encryptedAssertion };
            }
            else
            {
                response.Items = new object[] { assertion };
            }

            // Serialize the response.
            XmlDocument responseDoc = new XmlDocument();

            responseDoc.XmlResolver        = null;
            responseDoc.PreserveWhitespace = true;
            responseDoc.LoadXml(Serialization.SerializeToXmlString(response));

            if (encryptedAssertion == null)
            {
                // Sign the assertion inside the response message.
                signatureProvider.SignAssertion(responseDoc, assertion.ID, IDPConfig.IDPCertificate);
            }

            HttpPostBindingBuilder builder = new HttpPostBindingBuilder(endpoint);

            builder.Action = SAMLAction.SAMLResponse;

            builder.Response = responseDoc.OuterXml;

            builder.GetPage().ProcessRequest(Context);
            Context.Response.End();
        }
        public ActionResult Index(Account acct)
        {
            var payments =
                    from lngroup in acct.LineItemGroups
                    from lines in lngroup.LineItems
                    select new DTO.AmountToPayDTO() { AmountToPay=lines.AmountToPay, LineItemId=lines.Id };

                acctSvc.SaveAmountsToCart(acct.AccountNumber, new List<DTO.AmountToPayDTO>(payments.ToList()));

                string dest = Request["Destination"]; //string.Format(WebConfigurationManager.AppSettings["SPTargetURL"]);
                string samlService = Request["SAML"];

                // Create a SAML response with the user's local identity.
                SAMLResponse samlResponse = CreateSAMLResponse();

                ((SAMLAssertion)samlResponse.Assertions[0]).SetAttributeValue("AccountNumber", acct.AccountNumber);

                //Todo: fix names
                ((SAMLAssertion)samlResponse.Assertions[0]).SetAttributeValue("UserFirstName", "John" );
                ((SAMLAssertion)samlResponse.Assertions[0]).SetAttributeValue("UserLastName", "Smith");
                ((SAMLAssertion)samlResponse.Assertions[0]).SetAttributeValue("UserEMailAddress", Membership.GetUser(User.Identity.Name, true).Email );

                var encResponse = new EncryptedAssertion(
                    (SAMLAssertion)samlResponse.Assertions[0]
                    , (X509Certificate2)HttpContext.Application[FB.StrawPortal.MvcApplication.EncrypterX509Certificate]
                    , new EncryptionMethod(EncryptedXml.XmlEncAES256Url)
                );

                samlResponse.Assertions.RemoveAt(0);
                samlResponse.Assertions.Add(encResponse);

                // Send the SAML response to the service provider.
                SendSAMLResponse(samlResponse, dest, samlService);

                return new EmptyResult();
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try
            {
                // Extract the SP target url.
                string targetUrl = Request.QueryString["spUrl"];

                // Validate it.
                if (string.IsNullOrEmpty(targetUrl))
                {
                    return;
                }

                // Create a SAML response object.
                ComponentPro.Saml2.Response samlResponse = new ComponentPro.Saml2.Response();
                // Assign the consumer service url.
                samlResponse.Destination = ConsumerServiceUrl;
                Issuer issuer = new Issuer(GetAbsoluteUrl("~/"));
                samlResponse.Issuer = issuer;
                samlResponse.Status = new Status(SamlPrimaryStatusCode.Success, null);

                Assertion samlAssertion = new Assertion();
                samlAssertion.Issuer = issuer;

                // Use the local user's local identity.
                Subject                 subject                 = new Subject(new NameId(User.Identity.Name));
                SubjectConfirmation     subjectConfirmation     = new SubjectConfirmation(SamlSubjectConfirmationMethod.Bearer);
                SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();
                subjectConfirmationData.Recipient           = ConsumerServiceUrl;
                subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
                subject.SubjectConfirmations.Add(subjectConfirmation);
                samlAssertion.Subject = subject;

                // Create a new authentication statement.
                AuthnStatement authnStatement = new AuthnStatement();
                authnStatement.AuthnContext = new AuthnContext();
                authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SamlAuthenticateContext.Password);
                samlAssertion.Statements.Add(authnStatement);

                // If you need to add custom attributes, uncomment the following code
                // #region Custom Attributes
                // AttributeStatement attributeStatement = new AttributeStatement();
                // attributeStatement.Attributes.Add(new ComponentPro.Saml2.Attribute("email", SamlAttributeNameFormat.Basic, null,
                // "*****@*****.**"));
                // attributeStatement.Attributes.Add(new ComponentPro.Saml2.Attribute("FirstName", SamlAttributeNameFormat.Basic, null,
                // "John"));
                // attributeStatement.Attributes.Add(new ComponentPro.Saml2.Attribute("LastName", SamlAttributeNameFormat.Basic, null,
                // "Smith"));

                // // Insert a custom token key to the SAML response.
                // attributeStatement.Attributes.Add(new ComponentPro.Saml2.Attribute("CustomTokenForVerification", SamlAttributeNameFormat.Basic, null,
                // "YourEncryptedTokenHere"));

                // samlAssertion.Statements.Add(attributeStatement);
                // #endregion


                // Define ENCRYPTEDSAML preprocessor flag if you wish to encrypt the SAML response.
#if ENCRYPTEDSAML
                // Load the certificate for the encryption.
                // Please make sure the file is in the root directory.
                X509Certificate2 encryptingCert = new X509Certificate2(Path.Combine(HttpRuntime.AppDomainAppPath, "EncryptionX509Certificate.cer"), "password");

                // Create an encrypted SAML assertion from the SAML assertion we have created.
                EncryptedAssertion encryptedSamlAssertion = new EncryptedAssertion(samlAssertion, encryptingCert, new System.Security.Cryptography.Xml.EncryptionMethod(SamlKeyAlgorithm.TripleDesCbc));

                // Add encrypted assertion to the SAML response object.
                samlResponse.Assertions.Add(encryptedSamlAssertion);
#else
                // Add assertion to the SAML response object.
                samlResponse.Assertions.Add(samlAssertion);
#endif

                // Get the previously loaded certificate.
                X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.CertKeyName];

                // Sign the SAML response with the certificate.
                samlResponse.Sign(x509Certificate);

                // Send the SAML response to the service provider.
                samlResponse.SendPostBindingForm(Response.OutputStream, ConsumerServiceUrl, targetUrl);
            }

            catch (Exception exception)
            {
                Trace.Write("IdentityProvider", "An Error occurred", exception);
            }
        }