public void ThrowsExceptionWhenXmlAttributeStatementAttributeAnyAttrSamlQualified()
            {
                // Arrange
                var saml20Assertion    = AssertionUtil.GetBasicAssertion();
                var statements         = new List <StatementAbstract>(saml20Assertion.Items);
                var attributeStatments = (AttributeStatement)statements.Find(x => x is AttributeStatement);
                var attribute          = (SamlAttribute)attributeStatments.Items[0];

                var doc = new XmlDocument();

                saml20Assertion.Items = statements.ToArray();

                foreach (var samlns in Saml20Constants.SamlNamespaces)
                {
                    attribute.AnyAttr = new[] { doc.CreateAttribute("someprefix", "SamlQualified", samlns) };

                    try
                    {
                        // Act
                        var assertion = new Saml20Assertion(AssertionUtil.ConvertAssertionToXml(saml20Assertion).DocumentElement, null, false, TestConfiguration.Configuration);
                        Assert.Fail("A SAML-qualified xml attribute extension on Attribute must not be valid");
                    }
                    catch (Saml20FormatException sfe)
                    {
                        Assert.AreEqual(sfe.Message, "Attribute extension xml attributes MUST NOT use a namespace reserved by SAML");
                    }
                }
            }
            [Ignore]    // TODO: test data needs fixing
            public void AddAttribute()
            {
                // Arrange
                var assertion  = new Saml20Assertion(AssertionUtil.LoadXmlDocument(@"Assertions\Saml2Assertion_01").DocumentElement, null, false, TestConfiguration.Configuration);
                var attributes = assertion.Attributes;

                // This needs to be addressed and is why the test is ignored. See the original Hg project
                attributes.Add(new SamlAttribute());

                var cert = AssertionUtil.GetCertificate();

                assertion.Sign(cert, null);

                assertion.CheckValid(new[] { cert.PublicKey.Key });

                // Verify that the modified assertion can survive complete serialization and deserialization.
                var assertionString = assertion.GetXml().OuterXml;

                var deserializedAssertionDoc = new XmlDocument {
                    PreserveWhitespace = true
                };

                deserializedAssertionDoc.Load(new StringReader(assertionString));

                var deserializedAssertion = new Saml20Assertion(deserializedAssertionDoc.DocumentElement, null, false, TestConfiguration.Configuration);

                Assert.IsNotNull(deserializedAssertion.GetSignatureKeys(), "Signing keys must be present");
                deserializedAssertion.CheckValid(new[] { cert.PublicKey.Key });
            }
Exemple #3
0
        public void TestSigning03()
        {
            // Load an unsigned assertion.
            var assertion = new Saml20Assertion(AssertionUtil.GetTestAssertion().DocumentElement, null, false);

            // Check that the assertion is not considered valid in any way.
            try
            {
                assertion.CheckValid(AssertionUtil.GetTrustedSigners(assertion.Issuer));
                Assert.Fail("Unsigned assertion was passed off as valid.");
            }
            catch
            {
                // Added to make resharper happy
                Assert.That(true);
            }

            var cert = new X509Certificate2(TestContext.CurrentContext.TestDirectory + @"\Certificates\sts_dev_certificate.pfx", "test1234");

            Assert.That(cert.HasPrivateKey, "Certificate no longer contains a private key. Modify test.");
            assertion.Sign(cert);

            // Check that the signature is now valid
            assertion.CheckValid(new[] { cert.PublicKey.Key });
        }
Exemple #4
0
            public void AddAttribute()
            {
                // Arrange
                var assertion  = new Saml20Assertion(AssertionUtil.LoadXmlDocument(TestContext.CurrentContext.TestDirectory + @"\Assertions\Saml2Assertion_01").DocumentElement, null, false);
                var attributes = assertion.Attributes;

                attributes.Add(new SamlAttribute());

                var cert = AssertionUtil.GetCertificate();

                assertion.Sign(cert);

                assertion.CheckValid(new[] { cert.PublicKey.Key });

                // Verify that the modified assertion can survive complete serialization and deserialization.
                var assertionString = assertion.GetXml().OuterXml;

                var deserializedAssertionDoc = new XmlDocument {
                    PreserveWhitespace = true
                };

                deserializedAssertionDoc.Load(new StringReader(assertionString));

                var deserializedAssertion = new Saml20Assertion(deserializedAssertionDoc.DocumentElement, null, false);

                Assert.IsNotNull(deserializedAssertion.GetSignatureKeys(), "Signing keys must be present");
                deserializedAssertion.CheckValid(new[] { cert.PublicKey.Key });
            }
            public void VerifySignatureByDefault()
            {
                // Arrange
                // Any key-containing algorithm will do - the basic assertion is NOT signed anyway
                var cert = new X509Certificate2(@"Certificates\sts_dev_certificate.pfx", "test1234");

                // Act
                var assertion = new Saml20Assertion(AssertionUtil.GetTestAssertion().DocumentElement, new[] { cert.PublicKey.Key }, false, TestConfiguration.Configuration);
            }
Exemple #6
0
        /// <summary>
        /// Generates an encrypted assertion and writes it to disk.
        /// </summary>
        public static void GenerateEncryptedAssertion()
        {
            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 cert         = new X509Certificate2(@"Certificates\sts_dev_certificate.pfx", "test1234");
            var 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.
            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
        }
            public void VerifySignatureByDefault()
            {
                // Arrange
                // Any key-containing algorithm will do - the basic assertion is NOT signed anyway
                var cert = new X509Certificate2(TestContext.CurrentContext.TestDirectory + @"\Certificates\sts_dev_certificate.pfx", "test1234");

                // Act
                Assert.Throws<InvalidOperationException>(() => new Saml20Assertion(AssertionUtil.GetTestAssertion().DocumentElement, new[] { cert.PublicKey.Key }, false),
                    "Document does not contain a signature to verify.");
            }
            public void ThrowsWhenSubjectMethodIsNotWellFormedUri()
            {
                // Arrange
                var saml20Assertion     = AssertionUtil.GetBasicAssertion();
                var subjectConfirmation = (SubjectConfirmation)Array.Find(saml20Assertion.Subject.Items, item => item is SubjectConfirmation);

                subjectConfirmation.Method = "IllegalMethod";

                // Act
                var assertion = new Saml20Assertion(AssertionUtil.ConvertAssertionToXml(saml20Assertion).DocumentElement, null, false, TestConfiguration.Configuration);
            }
            public void ThrowsWhenSubjectMethodIsNotWellFormedUri()
            {
                // Arrange
                var saml20Assertion = AssertionUtil.GetBasicAssertion();
                var subjectConfirmation = (SubjectConfirmation)Array.Find(saml20Assertion.Subject.Items, item => item is SubjectConfirmation);
                subjectConfirmation.Method = "IllegalMethod";

                // Act
                Assert.Throws<Saml20FormatException>(() => new Saml20Assertion(AssertionUtil.ConvertAssertionToXml(saml20Assertion).DocumentElement, null, false), 
                    "SubjectConfirmation element has Method attribute which is not a wellformed absolute uri.");
            }
            public void ThrowsExceptionWhenNoItemsArePresent()
            {
                // Arrange
                var saml20Assertion    = AssertionUtil.GetBasicAssertion();
                var attributeStatement = (AttributeStatement)Array.Find(saml20Assertion.Items, x => x is AttributeStatement);

                // Clear all the attributes.
                attributeStatement.Items = new object[0];

                // Act
                var assertion = new Saml20Assertion(AssertionUtil.ConvertAssertionToXml(saml20Assertion).DocumentElement, null, false, TestConfiguration.Configuration);
            }
        public void HasNoAssertionBeforeDecrypt()
        {
            // Arrange
            var doc  = AssertionUtil.LoadXmlDocument(TestContext.CurrentContext.TestDirectory + @"\Assertions\EncryptedAssertion_01");
            var cert = new X509Certificate2(TestContext.CurrentContext.TestDirectory + @"\Certificates\sts_dev_certificate.pfx", "test1234");

            // Act
            var encryptedAssertion = new Saml20EncryptedAssertion((RSA)cert.PrivateKey, doc);

            // Assert
            Assert.IsNull(encryptedAssertion.Assertion);
        }
            public void ThrowsExceptionWhenNoItemsArePresent()
            {
                // Arrange
                var saml20Assertion = AssertionUtil.GetBasicAssertion();
                var attributeStatement = (AttributeStatement)Array.Find(saml20Assertion.Items, x => x is AttributeStatement);

                // Clear all the attributes.
                attributeStatement.Items = new object[0];

                // Act
                Assert.Throws<Saml20FormatException>(() => new Saml20Assertion(AssertionUtil.ConvertAssertionToXml(saml20Assertion).DocumentElement, null, false),
                    "AttributeStatement MUST contain at least one Attribute or EncryptedAttribute");
            }
            public void ThrowsWhenSubjectElementIsNotPresent()
            {
                // Arrange
                var saml20Assertion = AssertionUtil.GetBasicAssertion();
                var subjectConfirmation = (SubjectConfirmation)Array.Find(saml20Assertion.Subject.Items, item => item is SubjectConfirmation);
                subjectConfirmation.SubjectConfirmationData.NotOnOrAfter = DateTime.UtcNow;
                subjectConfirmation.SubjectConfirmationData.NotBefore = null;
                saml20Assertion.Subject = null;

                // Act
                Assert.Throws<Saml20FormatException>(() => new Saml20Assertion(AssertionUtil.ConvertAssertionToXml(saml20Assertion).DocumentElement, null, false), 
                    "AuthnStatement, AuthzDecisionStatement and AttributeStatement require a subject.");
            }
            public void ThrowsWhenAuthnContextClassRefIsNotWellFormedUri()
            {
                // Arrange
                var saml20Assertion = AssertionUtil.GetBasicAssertion();
                var authnStatement = (AuthnStatement)Array.Find(saml20Assertion.Items, stmnt => stmnt is AuthnStatement);

                var index = Array.FindIndex(authnStatement.AuthnContext.Items, o => o is string && o.ToString() == "urn:oasis:names:tc:SAML:2.0:ac:classes:X509");
                authnStatement.AuthnContext.Items[index] = "Hallelujagobble!!";

                // Act
                Assert.Throws<Saml20FormatException>(() => new Saml20Assertion(AssertionUtil.ConvertAssertionToXml(saml20Assertion).DocumentElement, null, false),
                    "AuthnContextClassRef has a value which is not a wellformed absolute uri");
            }
Exemple #15
0
        public void AssertionCanBeSignedAndVerified()
        {
            // Arrange
            var token = AssertionUtil.GetTestAssertion();

            SignDocument(token);

            // Act
            var verified = VerifySignature(token);

            // Assert
            Assert.That(verified);
        }
            public void CanDecryptAssertionWithPeerIncludedKeys()
            {
                // Arrange
                var doc  = AssertionUtil.LoadXmlDocument(@"Assertions\EncryptedAssertion_02");
                var cert = new X509Certificate2(@"Certificates\sts_dev_certificate.pfx", "test1234");
                var encryptedAssertion = new Saml20EncryptedAssertion((RSA)cert.PrivateKey, doc);

                // Act
                encryptedAssertion.Decrypt();

                // Assert
                Assert.IsNotNull(encryptedAssertion.Assertion);
            }
            public void ThrowsWhenAuthnContextClassRefIsNotWellFormedUri()
            {
                // Arrange
                var saml20Assertion = AssertionUtil.GetBasicAssertion();
                var authnStatement  = (AuthnStatement)Array.Find(saml20Assertion.Items, stmnt => stmnt is AuthnStatement);

                var index = Array.FindIndex(authnStatement.AuthnContext.Items, o => o is string && o.ToString() == "urn:oasis:names:tc:SAML:2.0:ac:classes:X509");

                authnStatement.AuthnContext.Items[index] = "Hallelujagobble!!";

                // Act
                var assertion = new Saml20Assertion(AssertionUtil.ConvertAssertionToXml(saml20Assertion).DocumentElement, null, false, TestConfiguration.Configuration);
            }
            public void CanDecryptAssertionWithPeerIncludedKeysWithoutSpecifiedEncryptionMethod()
            {
                // Arrange
                var doc  = AssertionUtil.LoadXmlDocument(TestContext.CurrentContext.TestDirectory + @"\Assertions\EncryptedAssertion_03");
                var cert = new X509Certificate2(TestContext.CurrentContext.TestDirectory + @"\Certificates\sts_dev_certificate.pfx", "test1234");
                var encryptedAssertion = new Saml20EncryptedAssertion((RSA)cert.PrivateKey, doc);

                // Act
                encryptedAssertion.Decrypt();

                // Assert
                Assert.IsNotNull(encryptedAssertion.Assertion);
            }
            public void CanReadAttributes()
            {
                // Act
                var assertion = new Saml20Assertion(AssertionUtil.LoadXmlDocument(@"Assertions\Saml2Assertion_01").DocumentElement, null, false, TestConfiguration.Configuration);

                // Assert
                CollectionAssert.IsNotEmpty(assertion.Attributes);
                Assert.AreEqual(4, assertion.Attributes.Count);
                foreach (var sa in assertion.Attributes)
                {
                    Assert.That(sa.AttributeValue.Length != 0, "Attribute should have a value");
                }
            }
            public void ThrowsWhenSubjectElementIsNotPresent()
            {
                // Arrange
                var saml20Assertion     = AssertionUtil.GetBasicAssertion();
                var subjectConfirmation = (SubjectConfirmation)Array.Find(saml20Assertion.Subject.Items, item => item is SubjectConfirmation);

                subjectConfirmation.SubjectConfirmationData.NotOnOrAfter = DateTime.UtcNow;
                subjectConfirmation.SubjectConfirmationData.NotBefore    = null;
                saml20Assertion.Subject = null;

                // Act
                var assertion = new Saml20Assertion(AssertionUtil.ConvertAssertionToXml(saml20Assertion).DocumentElement, null, false, TestConfiguration.Configuration);
            }
            public void CanDecryptAssertionWithPeerIncludedAesKeys()
            {
                // Arrange
                var doc  = AssertionUtil.LoadXmlDocument(TestContext.CurrentContext.TestDirectory + @"\Assertions\EncryptedAssertion_05");
                var cert = new X509Certificate2(TestContext.CurrentContext.TestDirectory + @"\Certificates\sts_dev_certificate.pfx", "test1234");
                var encryptedAssertion = new Saml20EncryptedAssertion((RSA)cert.PrivateKey, doc);

                // Act
                encryptedAssertion.Decrypt();

                // Assert
                Assert.IsNotNull(encryptedAssertion.Assertion);
                Assert.AreEqual(1, encryptedAssertion.Assertion.GetElementsByTagName(Assertion.ElementName, Saml20Constants.Assertion).Count);
            }
            public void CanDecryptAssertion()
            {
                // Arrange
                var doc  = AssertionUtil.LoadXmlDocument(@"Assertions\EncryptedAssertion_01");
                var cert = new X509Certificate2(@"Certificates\sts_dev_certificate.pfx", "test1234");
                var encryptedAssertion = new Saml20EncryptedAssertion((RSA)cert.PrivateKey, doc);

                // Act
                encryptedAssertion.Decrypt();
                var assertion = new Saml20Assertion(encryptedAssertion.Assertion.DocumentElement, null, false, TestConfiguration.Configuration);

                // Assert
                Assert.IsNotNull(encryptedAssertion.Assertion);
            }
        public void DecryptPingAssertion()
        {
            // Load the assertion
            var doc = new XmlDocument();

            doc.Load(File.OpenRead(@"c:\tmp\pingassertion.txt"));

            var xe = GetElement(EncryptedAssertion.ElementName, Saml20Constants.Assertion, doc);

            var doc2 = new XmlDocument();

            doc2.AppendChild(doc2.ImportNode(xe, true));

            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

            store.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection coll = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName,
                                                                      "CN=SafewhereTest_SFS, O=Safewhere, C=DK",
                                                                      true);

            Assert.That(coll.Count == 1);

            var cert = coll[0];

            var encass = new Saml20EncryptedAssertion((RSA)cert.PrivateKey, doc2);

            encass.Decrypt();

            var writer = new XmlTextWriter(Console.Out)
            {
                Formatting  = Formatting.Indented,
                Indentation = 3,
                IndentChar  = ' '
            };

            encass.Assertion.WriteTo(writer);
            writer.Flush();

            var assertion = new Saml20Assertion(encass.Assertion.DocumentElement, AssertionUtil.GetTrustedSigners(encass.Assertion.Attributes["Issuer"].Value), false);

            Assert.That(encass.Assertion != null);

            Console.WriteLine();
            foreach (SamlAttribute attribute in assertion.Attributes)
            {
                Console.WriteLine(attribute.Name + " : " + attribute.AttributeValue[0]);
            }
        }
            //[ExpectedException(typeof(Saml20Exception), ExpectedMessage = "Assertion is no longer valid.")]
            public void CanDecryptFOBSAssertion()
            {
                // Arrange
                var doc           = AssertionUtil.LoadBase64EncodedXmlDocument(@"Assertions\fobs-assertion2");
                var encryptedList = doc.GetElementsByTagName(EncryptedAssertion.ElementName, Saml20Constants.Assertion);

                // Do some mock configuration.
                var idpSource = new IdentityProviders();
                var config    = new Saml2Configuration
                {
                    AllowedAudienceUris     = new System.Collections.Generic.List <Uri>(),
                    IdentityProvidersSource = idpSource
                };

                config.AllowedAudienceUris.Add(new Uri("https://saml.safewhere.net"));
                idpSource.AddByMetadataDirectory(@"Protocol\MetadataDocs\FOBS"); // Set it manually.

                var cert = new X509Certificate2(@"Certificates\SafewhereTest_SFS.pfx", "test1234");
                var encryptedAssertion = new Saml20EncryptedAssertion((RSA)cert.PrivateKey);

                encryptedAssertion.LoadXml((XmlElement)encryptedList[0]);

                // Act
                encryptedAssertion.Decrypt();

                // Retrieve metadata
                var assertion = new Saml20Assertion(encryptedAssertion.Assertion.DocumentElement, null, false, TestConfiguration.Configuration);
                var endp      = config.IdentityProvidersSource.GetById(assertion.Issuer);

                // Assert
                Assert.That(encryptedList.Count == 1);
                Assert.IsNotNull(endp, "Endpoint not found");
                Assert.IsNotNull(endp.Metadata, "Metadata not found");

                try
                {
                    assertion.CheckValid(AssertionUtil.GetTrustedSigners(assertion.Issuer));
                    Assert.Fail("Verification should fail. Token does not include its signing key.");
                }
                catch (InvalidOperationException)
                {
                }

                Assert.IsNull(assertion.SigningKey, "Signing key is already present on assertion. Modify test.");
                //Assert.IsTrue("We have tested this next test" == "");
                //Assert.That(assertion.CheckSignature(Saml20SignonHandler.GetTrustedSigners(endp.Metadata.GetKeys(KeyTypes.Signing), endp)));
                //Assert.IsNotNull(assertion.SigningKey, "Signing key was not set on assertion instance.");
            }
        public void CanEncryptAssertionFull()
        {
            // Arrange
            var encryptedAssertion = new Saml20EncryptedAssertion
            {
                SessionKeyAlgorithm = EncryptedXml.XmlEncAES128Url,
                Assertion           = AssertionUtil.GetTestAssertion()
            };

            var cert = new X509Certificate2(TestContext.CurrentContext.TestDirectory + @"\Certificates\sts_dev_certificate.pfx", "test1234");

            encryptedAssertion.TransportKey = (RSA)cert.PublicKey.Key;

            // Act
            encryptedAssertion.Encrypt();
            var encryptedAssertionXml = encryptedAssertion.GetXml();

            // Now decrypt the assertion, and verify that it recognizes the Algorithm used.
            var decrypter = new Saml20EncryptedAssertion((RSA)cert.PrivateKey);

            decrypter.LoadXml(encryptedAssertionXml.DocumentElement);

            // Set a wrong algorithm and make sure that the class gets it algorithm info from the assertion itself.
            decrypter.SessionKeyAlgorithm = EncryptedXml.XmlEncTripleDESUrl;
            decrypter.Decrypt();

            // Assert
            // Go through the children and look for the EncryptionMethod element, and verify its algorithm attribute.
            var encryptionMethodFound = false;

            foreach (XmlNode node in encryptedAssertionXml.GetElementsByTagName(Schema.XEnc.EncryptedData.ElementName, Saml20Constants.Xenc)[0].ChildNodes)
            {
                if (node.LocalName == Schema.XEnc.EncryptionMethod.ElementName && node.NamespaceURI == Saml20Constants.Xenc)
                {
                    var element = (XmlElement)node;
                    Assert.AreEqual(EncryptedXml.XmlEncAES128Url, element.GetAttribute("Algorithm"));
                    encryptionMethodFound = true;
                }
            }

            Assert.That(encryptionMethodFound, "Unable to find EncryptionMethod element in EncryptedData.");

            // Verify that the class has discovered the correct algorithm and set the SessionKeyAlgorithm property accordingly.
            Assert.AreEqual(EncryptedXml.XmlEncAES128Url, decrypter.SessionKeyAlgorithm);
            Assert.IsNotNull(decrypter.Assertion);
        }
            public void ThrowsExceptionWhenXmlAttributeStatementAttributeAnyAttrUnqualified()
            {
                // Arrange
                var saml20Assertion = AssertionUtil.GetBasicAssertion();
                var statements = new List<StatementAbstract>(saml20Assertion.Items);
                var attributeStatments = (AttributeStatement)statements.Find(x => x is AttributeStatement);
                var attribute = (SamlAttribute)attributeStatments.Items[0];

                var doc = new XmlDocument();
                attribute.AnyAttr = new[] { doc.CreateAttribute(string.Empty, "Nonqualified", string.Empty) };

                saml20Assertion.Items = statements.ToArray();

                // Act
                Assert.Throws<Saml20FormatException>(() => new Saml20Assertion(AssertionUtil.ConvertAssertionToXml(saml20Assertion).DocumentElement, null, false),
                    "Attribute extension xml attributes MUST BE namespace qualified");
            }
            public void ThrowsExceptionWhenXmlAttributeStatementEncryptedAttributeWithNoData()
            {
                // Arrange
                var saml20Assertion = AssertionUtil.GetBasicAssertion();
                var statements = new List<StatementAbstract>(saml20Assertion.Items);
                var attributeStatments = (AttributeStatement)statements.Find(x => x is AttributeStatement);

                var attributes = new List<object>(attributeStatments.Items);
                var ee = new EncryptedElement();
                attributes.Add(ee);
                attributeStatments.Items = attributes.ToArray();
                saml20Assertion.Items = statements.ToArray();

                // Act
                Assert.Throws<Saml20FormatException>(() => new Saml20Assertion(AssertionUtil.ConvertAssertionToXml(saml20Assertion).DocumentElement, null, false),
                    "An EncryptedAttribute MUST contain an xenc:EncryptedData element");
            }
            public void ThrowsExceptionWhenXmlAttributeStatementAttributeAnyAttrUnqualified()
            {
                // Arrange
                var saml20Assertion    = AssertionUtil.GetBasicAssertion();
                var statements         = new List <StatementAbstract>(saml20Assertion.Items);
                var attributeStatments = (AttributeStatement)statements.Find(x => x is AttributeStatement);
                var attribute          = (SamlAttribute)attributeStatments.Items[0];

                var doc = new XmlDocument();

                attribute.AnyAttr = new[] { doc.CreateAttribute(string.Empty, "Nonqualified", string.Empty) };

                saml20Assertion.Items = statements.ToArray();

                // Act
                new Saml20Assertion(AssertionUtil.ConvertAssertionToXml(saml20Assertion).DocumentElement, null, false, TestConfiguration.Configuration);
            }
            public void ThrowsExceptionWhenXmlAttributeStatementEncryptedAttributeWithNoData()
            {
                // Arrange
                var saml20Assertion    = AssertionUtil.GetBasicAssertion();
                var statements         = new List <StatementAbstract>(saml20Assertion.Items);
                var attributeStatments = (AttributeStatement)statements.Find(x => x is AttributeStatement);

                var attributes = new List <object>(attributeStatments.Items);
                var ee         = new EncryptedElement();

                attributes.Add(ee);
                attributeStatments.Items = attributes.ToArray();
                saml20Assertion.Items    = statements.ToArray();

                // Act
                var assertion = new Saml20Assertion(AssertionUtil.ConvertAssertionToXml(saml20Assertion).DocumentElement, null, false, TestConfiguration.Configuration);
            }
            public void CanDecryptFOBSAssertion()
            {
                // Arrange
                var doc           = AssertionUtil.LoadBase64EncodedXmlDocument(@"Assertions\fobs-assertion2");
                var encryptedList = doc.GetElementsByTagName(EncryptedAssertion.ElementName, Saml20Constants.Assertion);

                // Do some mock configuration.
                var config = Saml2Config.GetConfig();

                config.AllowedAudienceUris.Add(new AudienceUriElement {
                    Uri = "https://saml.safewhere.net"
                });
                config.IdentityProviders.MetadataLocation = @"Protocol\MetadataDocs\FOBS"; // Set it manually.
                Assert.That(Directory.Exists(config.IdentityProviders.MetadataLocation));

                var cert = new X509Certificate2(@"Certificates\SafewhereTest_SFS.pfx", "test1234");
                var encryptedAssertion = new Saml20EncryptedAssertion((RSA)cert.PrivateKey);

                encryptedAssertion.LoadXml((XmlElement)encryptedList[0]);

                // Act
                encryptedAssertion.Decrypt();

                // Retrieve metadata
                var assertion = new Saml20Assertion(encryptedAssertion.Assertion.DocumentElement, null, false);
                var endp      = config.IdentityProviders.FirstOrDefault(x => x.Id == assertion.Issuer);

                // Assert
                Assert.That(encryptedList.Count == 1);
                Assert.IsNotNull(endp, "Endpoint not found");
                Assert.IsNotNull(endp.Metadata, "Metadata not found");

                try
                {
                    assertion.CheckValid(AssertionUtil.GetTrustedSigners(assertion.Issuer));
                    Assert.Fail("Verification should fail. Token does not include its signing key.");
                }
                catch (InvalidOperationException)
                {
                }

                Assert.IsNull(assertion.SigningKey, "Signing key is already present on assertion. Modify test.");
                Assert.That(assertion.CheckSignature(Saml20SignonHandler.GetTrustedSigners(endp.Metadata.GetKeys(KeyTypes.Signing), endp)));
                Assert.IsNotNull(assertion.SigningKey, "Signing key was not set on assertion instance.");
            }