Ejemplo n.º 1
0
        private OpenIdConnectMessage TestJsonStringConstructor(string json, ExpectedException expectedException)
        {
            OpenIdConnectMessage openIdConnectMessage = null;

            try
            {
                openIdConnectMessage = new OpenIdConnectMessage(json);
                expectedException.ProcessNoException();
            }
            catch (Exception exception)
            {
                expectedException.ProcessException(exception);
            }

            return(openIdConnectMessage);
        }
Ejemplo n.º 2
0
 private void GetDocument(string address, IDocumentRetriever docRetriever, ExpectedException ee)
 {
     try
     {
         string doc = docRetriever.GetDocumentAsync(address, CancellationToken.None).Result;
         ee.ProcessNoException();
     }
     catch (AggregateException ex)
     {
         ex.Handle((x) =>
         {
             ee.ProcessException(x);
             return(true);
         });
     }
 }
Ejemplo n.º 3
0
#pragma warning restore CS3016 // Arrays as attribute arguments is not CLS-compliant
        public void CreateJWETokens(string testId, string jweToken, TokenValidationParameters validationParameters, JwtPayload expectedPayload, ExpectedException ee)
        {
            var handler = new JwtSecurityTokenHandler();

            handler.InboundClaimTypeMap.Clear();
            try
            {
                SecurityToken token           = null;
                var           claimsPrincipal = handler.ValidateToken(jweToken, validationParameters, out token);
                ee.ProcessNoException();
                var outerToken = token as JwtSecurityToken;

                Assert.True(outerToken != null, "ValidateToken should not return a null token for the JWE token.");
                TestUtilities.CallAllPublicInstanceAndStaticPropertyGets(outerToken, testId);

                Assert.True(outerToken.InnerToken != null, "ValidateToken should not return a null token for the inner JWE token.");
                TestUtilities.CallAllPublicInstanceAndStaticPropertyGets(outerToken.InnerToken, testId);

                var context = new CompareContext();
                if (!IdentityComparer.AreEqual(outerToken.Payload, outerToken.InnerToken.Payload, context))
                {
                    context.Diffs.Add("outerToken.Payload != outerToken.InnerToken.Payload");
                }

                foreach (KeyValuePair <string, object> claim in expectedPayload)
                {
                    if (!outerToken.Payload.ContainsKey(claim.Key))
                    {
                        context.Diffs.Add(String.Format("expectedPayload claim {0} : {1} doesn't exist in outerToken.Payload", claim.Key, claim.Value));
                    }
                    else
                    {
                        if ((outerToken.Payload[claim.Key] != null && !outerToken.Payload[claim.Key].Equals(claim.Value)) || (outerToken.Payload[claim.Key] == null && claim.Value != null))
                        {
                            context.Diffs.Add(String.Format("expectedPayload claim {0} doesn't match in outerToken.Payload. Expected value: {1}. Outer token value: {2}", claim.Key, claim.Value, outerToken.Payload[claim.Key]));
                        }
                    }
                }

                TestUtilities.AssertFailIfErrors(string.Format(CultureInfo.InvariantCulture, "CreateJWETokens: "), context.Diffs);
            }
            catch (Exception ex)
            {
                ee.ProcessException(ex);
            }
        }
        private ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, ISecurityTokenValidator tokenValidator, ExpectedException expectedException)
        {
            ClaimsPrincipal princiapl = null;

            try
            {
                SecurityToken validatedToken;
                princiapl = tokenValidator.ValidateToken(securityToken, validationParameters, out validatedToken);
                expectedException.ProcessNoException();
            }
            catch (Exception exception)
            {
                expectedException.ProcessException(exception);
            }

            return(princiapl);
        }
        private async Task<OpenIdConnectConfiguration> GetConfigurationAsync(string uri, ExpectedException expectedException, OpenIdConnectConfiguration expectedConfiguration, CompareContext context)
        {
            OpenIdConnectConfiguration openIdConnectConfiguration = null;
            try
            {
                openIdConnectConfiguration = await OpenIdConnectConfigurationRetriever.GetAsync(uri, new FileDocumentRetriever(), CancellationToken.None);
                expectedException.ProcessNoException(context);
            }
            catch (Exception exception)
            {
                expectedException.ProcessException(exception, context.Diffs);
            }

            if (expectedConfiguration != null)
                IdentityComparer.AreEqual(openIdConnectConfiguration, expectedConfiguration, context);

            return openIdConnectConfiguration;
        }
        private async Task<OpenIdConnectConfiguration> GetConfigurationFromHttpAsync(string uri, ExpectedException expectedException, OpenIdConnectConfiguration expectedConfiguration = null)
        {
            OpenIdConnectConfiguration openIdConnectConfiguration = null;
            try
            {
                openIdConnectConfiguration = await OpenIdConnectConfigurationRetriever.GetAsync(uri, CancellationToken.None);
                expectedException.ProcessNoException();
            }
            catch (Exception exception)
            {
                expectedException.ProcessException(exception);
            }

            if (expectedConfiguration != null)
            {
                Assert.True(IdentityComparer.AreEqual(openIdConnectConfiguration, expectedConfiguration));
            }

            return openIdConnectConfiguration;
        }
        private async Task<OpenIdConnectConfiguration> GetConfigurationFromMixedAsync(string primaryDocument, ExpectedException expectedException, OpenIdConnectConfiguration expectedConfiguration = null)
        {
            OpenIdConnectConfiguration openIdConnectConfiguration = null;
            try
            {
                openIdConnectConfiguration = await OpenIdConnectConfigurationRetriever.GetAsync("primary",
                    new TestDocumentRetriever(primaryDocument, new FileDocumentRetriever()), CancellationToken.None);
                expectedException.ProcessNoException();
            }
            catch (Exception exception)
            {
                expectedException.ProcessException(exception);
            }

            if (expectedConfiguration != null)
            {
                Assert.True(IdentityComparer.AreEqual(openIdConnectConfiguration, expectedConfiguration));
            }

            return openIdConnectConfiguration;
        }
Ejemplo n.º 8
0
        public void Constructors()
        {
            WsFederationMessage wsFederationMessage = new WsFederationMessage();

            Assert.AreEqual(wsFederationMessage.IssuerAddress, string.Empty);

            wsFederationMessage = new WsFederationMessage("http://www.got.jwt.com");
            Assert.AreEqual(wsFederationMessage.IssuerAddress, "http://www.got.jwt.com");

            ExpectedException expectedException = ExpectedException.ArgumentNullException("issuerAddress");

            try
            {
                wsFederationMessage = new WsFederationMessage((string)null);
                expectedException.ProcessNoException();
            }
            catch (Exception exception)
            {
                expectedException.ProcessException(exception);
            }
        }
Ejemplo n.º 9
0
#pragma warning restore CS3016 // Arrays as attribute arguments is not CLS-compliant
        public void RoundTripJWETokens(string testId, SecurityTokenDescriptor tokenDescriptor, TokenValidationParameters validationParameters, ExpectedException ee)
        {
            var handler = new JwtSecurityTokenHandler();

            handler.InboundClaimTypeMap.Clear();
            var jweCreatedInMemory = handler.CreateJwtSecurityToken(tokenDescriptor);

            try
            {
                SecurityToken token           = null;
                var           claimsPrincipal = handler.ValidateToken(jweCreatedInMemory.RawData, validationParameters, out token);
                ee.ProcessNoException();
                var outerToken = token as JwtSecurityToken;

                Assert.True(outerToken != null, "ValidateToken should not return a null token for the JWE token.");
                TestUtilities.CallAllPublicInstanceAndStaticPropertyGets(outerToken, testId);

                Assert.True(outerToken.InnerToken != null, "ValidateToken should not return a null token for the inner JWE token.");
                TestUtilities.CallAllPublicInstanceAndStaticPropertyGets(outerToken.InnerToken, testId);

                var context = new CompareContext();
                if (!IdentityComparer.AreEqual(jweCreatedInMemory.Payload, outerToken.Payload, context))
                {
                    context.Diffs.Add("jweCreatedInMemory.Payload != jweValidated.Payload");
                }

                if (!IdentityComparer.AreEqual(jweCreatedInMemory.Payload, outerToken.InnerToken.Payload, context))
                {
                    context.Diffs.Add("jweCreatedInMemory.Payload != jweValidated.InnerToken.Payload");
                }

                TestUtilities.AssertFailIfErrors(string.Format(CultureInfo.InvariantCulture, "RoundTripJWETokens: "), context.Diffs);
            }
            catch (Exception ex)
            {
                ee.ProcessException(ex);
            }
        }
Ejemplo n.º 10
0
        public void Publics()
        {
            string value1 = "value1";
            string value2 = "value2";
            string param1 = "param1";
            string param2 = "param2";

            AuthenticationProtocolMessage authenticationProtocolMessage = new DerivedAuthenticationProtocolMessage()
            {
                IssuerAddress = "http://www.gotjwt.com"
            };
            ExpectedException expectedException = ExpectedException.ArgumentNullException(substringExpected: "parameter");

            try
            {
                authenticationProtocolMessage.GetParameter(null);
                expectedException.ProcessNoException();
            }
            catch (Exception exception)
            {
                expectedException.ProcessException(exception);
            }

            expectedException = ExpectedException.ArgumentNullException(substringExpected: "parameter");
            try
            {
                authenticationProtocolMessage.RemoveParameter(null);
                expectedException.ProcessNoException();
            }
            catch (Exception exception)
            {
                expectedException.ProcessException(exception);
            }

            expectedException = ExpectedException.ArgumentNullException(substringExpected: "parameter");
            try
            {
                authenticationProtocolMessage.SetParameter(null, null);
                expectedException.ProcessNoException();
            }
            catch (Exception exception)
            {
                expectedException.ProcessException(exception);
            }

            authenticationProtocolMessage.SetParameter(param1, value1);
            authenticationProtocolMessage.RemoveParameter(param2);
            Assert.Equal(authenticationProtocolMessage.GetParameter(param1), value1);

            authenticationProtocolMessage.RemoveParameter(param1);
            Assert.Null(authenticationProtocolMessage.GetParameter(param1));

            authenticationProtocolMessage.SetParameter(param1, value1);
            authenticationProtocolMessage.SetParameter(param1, value2);
            authenticationProtocolMessage.SetParameter(param2, value2);
            authenticationProtocolMessage.SetParameter(param2, value1);

            Assert.Equal(authenticationProtocolMessage.GetParameter(param1), value2);
            Assert.Equal(authenticationProtocolMessage.GetParameter(param2), value1);

            authenticationProtocolMessage = new DerivedAuthenticationProtocolMessage()
            {
                IssuerAddress = "http://www.gotjwt.com"
            };
            authenticationProtocolMessage.SetParameter("bob", "     ");

            string queryString = authenticationProtocolMessage.BuildRedirectUrl();

            Assert.NotNull(queryString);
            Assert.Contains("bob", queryString);

            authenticationProtocolMessage.IssuerAddress = string.Empty;
            queryString = authenticationProtocolMessage.BuildRedirectUrl();
            Assert.NotNull(queryString);
        }
Ejemplo n.º 11
0
        public void GetConfiguration()
        {
            FileDocumentRetriever docRetriever = new FileDocumentRetriever();
            ConfigurationManager <OpenIdConnectConfiguration> configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever);

            // AutomaticRefreshInterval interval should return same config.
            OpenIdConnectConfiguration configuration = configManager.GetConfigurationAsync().Result;

            TestUtilities.SetField(configManager, "_metadataAddress", "OpenIdConnectMetadata2.json");
            OpenIdConnectConfiguration configuration2 = configManager.GetConfigurationAsync().Result;

            Assert.True(IdentityComparer.AreEqual(configuration, configuration2));
            Assert.True(object.ReferenceEquals(configuration, configuration2));

            // AutomaticRefreshInterval should pick up new bits.
            configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever);
            TestUtilities.SetField(configManager, "_automaticRefreshInterval", TimeSpan.FromMilliseconds(1));
            configuration = configManager.GetConfigurationAsync().Result;
            TestUtilities.SetField(configManager, "_lastRefresh", DateTimeOffset.UtcNow - TimeSpan.FromHours(1));
            TestUtilities.SetField(configManager, "_metadataAddress", "OpenIdConnectMetadata2.json");
            configManager.RequestRefresh();
            configuration2 = configManager.GetConfigurationAsync().Result;
            Assert.False(IdentityComparer.AreEqual(configuration, configuration2));
            Assert.False(object.ReferenceEquals(configuration, configuration2));

            // RefreshInterval is set to MaxValue
            configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever);
            configuration = configManager.GetConfigurationAsync().Result;
            configManager.RefreshInterval = TimeSpan.MaxValue;
            TestUtilities.SetField(configManager, "_metadataAddress", "OpenIdConnectMetadata2.json");
            configuration2 = configManager.GetConfigurationAsync().Result;
            Assert.True(IdentityComparer.AreEqual(configuration, configuration2));
            Assert.True(object.ReferenceEquals(configuration, configuration2));

            // Refresh should have no effect
            configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever);
            configuration = configManager.GetConfigurationAsync().Result;
            configManager.RefreshInterval = TimeSpan.FromHours(10);
            configManager.RequestRefresh();
            configuration2 = configManager.GetConfigurationAsync().Result;
            Assert.True(IdentityComparer.AreEqual(configuration, configuration2));
            Assert.True(object.ReferenceEquals(configuration, configuration2));

            // Refresh should force pickup of new config
            configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever);
            configuration = configManager.GetConfigurationAsync().Result;
            TestUtilities.SetField(configManager, "_lastRefresh", DateTimeOffset.UtcNow - TimeSpan.FromHours(1));
            configManager.RequestRefresh();
            TestUtilities.SetField(configManager, "_metadataAddress", "OpenIdConnectMetadata2.json");
            configuration2 = configManager.GetConfigurationAsync().Result;
            Assert.False(object.ReferenceEquals(configuration, configuration2));
            Assert.False(IdentityComparer.AreEqual(configuration, configuration2));

            // Refresh set to MaxValue
            configManager.RefreshInterval = TimeSpan.MaxValue;
            configuration = configManager.GetConfigurationAsync().Result;
            Assert.True(object.ReferenceEquals(configuration, configuration2));
            Assert.True(IdentityComparer.AreEqual(configuration, configuration2));

            // get configuration from http address, should throw
            configManager = new ConfigurationManager <OpenIdConnectConfiguration>("http://someaddress.com", new OpenIdConnectConfigurationRetriever());
            ExpectedException ee = new ExpectedException(typeof(InvalidOperationException), "IDX10803:", typeof(ArgumentException));

            try
            {
                configuration = configManager.GetConfigurationAsync().Result;
                ee.ProcessNoException();
            }
            catch (AggregateException ex)
            {
                // this should throw, because last configuration retrived was null
                Assert.Throws <AggregateException>(() => configuration = configManager.GetConfigurationAsync().Result);

                ex.Handle((x) =>
                {
                    ee.ProcessException(x);
                    return(true);
                });
            }
        }
Ejemplo n.º 12
0
        public void RoundTripSamlPSignatureAfterAssertion()
        {
            var context = new CompareContext($"{this}.RoundTripSamlPSignatureAfterAssertion");
            ExpectedException expectedException = ExpectedException.NoExceptionExpected;
            var samlpTokenKey = KeyingMaterial.RsaSigningCreds_4096_Public.Key;
            var samlpTokenSigningCredentials = KeyingMaterial.RsaSigningCreds_4096;
            var samlpKey = KeyingMaterial.RsaSigningCreds_2048_Public.Key;
            var samlpSigningCredentials = KeyingMaterial.RsaSigningCreds_2048;

            try
            {
                // write samlp
                var settings = new XmlWriterSettings
                {
                    Encoding = new UTF8Encoding(false)
                };
                var buffer = new MemoryStream();
                var esw    = new EnvelopedSignatureWriter(XmlWriter.Create(buffer, settings), samlpSigningCredentials, "id-uAOhNLe7abGB6WGPk");
                esw.WriteStartElement("ns0", "Response", "urn:oasis:names:tc:SAML:2.0:protocol");

                esw.WriteAttributeString("ns1", "urn:oasis:names:tc:SAML:2.0:assertion");
                esw.WriteAttributeString("ns2", "http://www.w3.org/2000/09/xmldsig#");
                esw.WriteAttributeString("Destination", "https://tnia.eidentita.cz/fpsts/processRequest.aspx");
                esw.WriteAttributeString("ID", "id-uAOhNLe7abGB6WGPk");
                esw.WriteAttributeString("InResponseTo", "ida5714d006fcc430c92aacf34ab30b166");
                esw.WriteAttributeString("IssueInstant", "2019-04-08T10:30:49Z");
                esw.WriteAttributeString("Version", "2.0");
                esw.WriteStartElement("ns1", "Issuer");
                esw.WriteAttributeString("Format", "urn:oasis:names:tc:SAML:2.0:nameid-format:entity");
                esw.WriteString("https://mojeid.regtest.nic.cz/saml/idp.xml");
                esw.WriteEndElement();
                esw.WriteStartElement("ns0", "Status", null);
                esw.WriteStartElement("ns0", "StatusCode", null);
                esw.WriteAttributeString("Value", "urn:oasis:names:tc:SAML:2.0:status:Success");
                esw.WriteEndElement();
                esw.WriteEndElement();
                Saml2Serializer samlSerializer = new Saml2Serializer();
                Saml2Assertion  assertion      = CreateAssertion(samlpTokenSigningCredentials);
                samlSerializer.WriteAssertion(esw, assertion);
                esw.WriteSignature();
                esw.WriteEndElement();
                var xml = Encoding.UTF8.GetString(buffer.ToArray());

                // read samlp and verify signatures
                XmlReader         reader       = XmlUtilities.CreateDictionaryReader(xml);
                IXmlElementReader tokenReaders = new TokenReaders(new List <SecurityTokenHandler> {
                    new Saml2SecurityTokenHandler()
                });
                EnvelopedSignatureReader envelopedReader = new EnvelopedSignatureReader(reader, tokenReaders);

                while (envelopedReader.Read())
                {
                    ;
                }

                foreach (var item in tokenReaders.Items)
                {
                    if (item is Saml2SecurityToken samlToken)
                    {
                        samlToken.Assertion.Signature.Verify(samlpTokenKey);
                    }
                }

                envelopedReader.Signature.Verify(samlpKey, samlpKey.CryptoProviderFactory);
                expectedException.ProcessNoException(context);
            }
            catch (Exception ex)
            {
                expectedException.ProcessException(ex, context);
            }

            TestUtilities.AssertFailIfErrors(context);
        }
Ejemplo n.º 13
0
        public void RoundTripJWETokens(string testId, SecurityTokenDescriptor tokenDescriptor, TokenValidationParameters validationParameters, ExpectedException ee)
        {
            var handler = new JwtSecurityTokenHandler();

            handler.InboundClaimTypeMap.Clear();
            var jweCreatedInMemory  = handler.CreateJwtSecurityToken(tokenDescriptor);
            var jweCreatedInMemory2 = handler.CreateJwtSecurityToken
                                      (
                tokenDescriptor.Issuer,
                tokenDescriptor.Audience,
                tokenDescriptor.Subject,
                tokenDescriptor.NotBefore,
                tokenDescriptor.Expires,
                tokenDescriptor.IssuedAt,
                tokenDescriptor.SigningCredentials,
                tokenDescriptor.EncryptingCredentials
                                      );

            try
            {
                SecurityToken token           = null;
                var           claimsPrincipal = handler.ValidateToken(jweCreatedInMemory.RawData, validationParameters, out token);
                ee.ProcessNoException();
                var outerToken = token as JwtSecurityToken;

                Assert.True(outerToken != null, "ValidateToken should not return a null token for the JWE token.");
                TestUtilities.CallAllPublicInstanceAndStaticPropertyGets(outerToken, testId);

                Assert.True(outerToken.InnerToken != null, "ValidateToken should not return a null token for the inner JWE token.");
                TestUtilities.CallAllPublicInstanceAndStaticPropertyGets(outerToken.InnerToken, testId);

                var context = new CompareContext();
                context.PropertiesToIgnoreWhenComparing = new Dictionary <Type, List <string> >
                {
                    { typeof(JwtHeader), new List <string> {
                          "Item"
                      } },
                    { typeof(JwtPayload), new List <string> {
                          "Item"
                      } }
                };

                if (!IdentityComparer.AreEqual(jweCreatedInMemory.Payload, outerToken.Payload, context))
                {
                    context.Diffs.Add("jweCreatedInMemory.Payload != jweValidated.Payload");
                }

                if (!IdentityComparer.AreEqual(jweCreatedInMemory.Payload, jweCreatedInMemory2.Payload, context))
                {
                    context.Diffs.Add("jweCreatedInMemory.Payload != jweCreatedInMemory2.Payload");
                }

                if (!IdentityComparer.AreEqual(jweCreatedInMemory.Payload, outerToken.InnerToken.Payload, context))
                {
                    context.Diffs.Add("jweCreatedInMemory.Payload != jweValidated.InnerToken.Payload");
                }

                TestUtilities.AssertFailIfErrors(string.Format(CultureInfo.InvariantCulture, "RoundTripJWETokens: "), context.Diffs);
            }
            catch (Exception ex)
            {
                ee.ProcessException(ex);
            }
        }
Ejemplo n.º 14
0
        public void GetConfiguration()
        {
            var docRetriever  = new FileDocumentRetriever();
            var configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever);
            var context       = new CompareContext($"{this}.GetConfiguration");

            // AutomaticRefreshInterval interval should return same config.
            var configuration = configManager.GetConfigurationAsync().Result;

            TestUtilities.SetField(configManager, "_metadataAddress", "OpenIdConnectMetadata2.json");
            var configuration2 = configManager.GetConfigurationAsync().Result;

            IdentityComparer.AreEqual(configuration, configuration2, context);
            if (!object.ReferenceEquals(configuration, configuration2))
            {
                context.Diffs.Add("!object.ReferenceEquals(configuration, configuration2)");
            }

            // AutomaticRefreshInterval should pick up new bits.
            configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever);
            TestUtilities.SetField(configManager, "_automaticRefreshInterval", TimeSpan.FromMilliseconds(1));
            configuration = configManager.GetConfigurationAsync().Result;
            TestUtilities.SetField(configManager, "_lastRefresh", DateTimeOffset.UtcNow - TimeSpan.FromHours(1));
            TestUtilities.SetField(configManager, "_metadataAddress", "OpenIdConnectMetadata2.json");
            configManager.RequestRefresh();
            configuration2 = configManager.GetConfigurationAsync().Result;
            if (IdentityComparer.AreEqual(configuration, configuration2))
            {
                context.Diffs.Add("IdentityComparer.AreEqual(configuration, configuration2)");
            }

            if (object.ReferenceEquals(configuration, configuration2))
            {
                context.Diffs.Add("object.ReferenceEquals(configuration, configuration2) (2)");
            }

            // RefreshInterval is set to MaxValue
            configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever);
            configuration = configManager.GetConfigurationAsync().Result;
            configManager.RefreshInterval = TimeSpan.MaxValue;
            TestUtilities.SetField(configManager, "_metadataAddress", "OpenIdConnectMetadata2.json");
            configuration2 = configManager.GetConfigurationAsync().Result;
            IdentityComparer.AreEqual(configuration, configuration2, context);
            if (!object.ReferenceEquals(configuration, configuration2))
            {
                context.Diffs.Add("!object.ReferenceEquals(configuration, configuration2) (3)");
            }

            // Refresh should have no effect
            configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever);
            configuration = configManager.GetConfigurationAsync().Result;
            configManager.RefreshInterval = TimeSpan.FromHours(10);
            configManager.RequestRefresh();
            configuration2 = configManager.GetConfigurationAsync().Result;
            IdentityComparer.AreEqual(configuration, configuration2, context);
            if (!object.ReferenceEquals(configuration, configuration2))
            {
                context.Diffs.Add("!object.ReferenceEquals(configuration, configuration2) (4)");
            }

            // Refresh should force pickup of new config
            configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever);
            configuration = configManager.GetConfigurationAsync().Result;
            TestUtilities.SetField(configManager, "_lastRefresh", DateTimeOffset.UtcNow - TimeSpan.FromHours(1));
            configManager.RequestRefresh();
            TestUtilities.SetField(configManager, "_metadataAddress", "OpenIdConnectMetadata2.json");
            configuration2 = configManager.GetConfigurationAsync().Result;
            if (IdentityComparer.AreEqual(configuration, configuration2))
            {
                context.Diffs.Add("IdentityComparer.AreEqual(configuration, configuration2), should be different");
            }

            if (object.ReferenceEquals(configuration, configuration2))
            {
                context.Diffs.Add("object.ReferenceEquals(configuration, configuration2)");
            }

            // Refresh set to MaxValue
            configManager.RefreshInterval = TimeSpan.MaxValue;
            configuration = configManager.GetConfigurationAsync().Result;
            IdentityComparer.AreEqual(configuration, configuration2, context);
            if (!object.ReferenceEquals(configuration, configuration2))
            {
                context.Diffs.Add("!object.ReferenceEquals(configuration, configuration2)");
            }

            // get configuration from http address, should throw
            configManager = new ConfigurationManager <OpenIdConnectConfiguration>("http://someaddress.com", new OpenIdConnectConfigurationRetriever());
            var ee = new ExpectedException(typeof(InvalidOperationException), "IDX20803:", typeof(ArgumentException));

            try
            {
                configuration = configManager.GetConfigurationAsync().Result;
                ee.ProcessNoException(context);
            }
            catch (AggregateException ex)
            {
                // this should throw, because last configuration retrived was null
                Assert.Throws <AggregateException>(() => configuration = configManager.GetConfigurationAsync().Result);

                ex.Handle((x) =>
                {
                    ee.ProcessException(x, context);
                    return(true);
                });
            }

            // get configuration from https address, should throw
            configManager = new ConfigurationManager <OpenIdConnectConfiguration>("https://someaddress.com", new OpenIdConnectConfigurationRetriever());
            ee            = new ExpectedException(typeof(InvalidOperationException), "IDX20803:", typeof(IOException));
            try
            {
                configuration = configManager.GetConfigurationAsync().Result;
                ee.ProcessNoException(context);
            }
            catch (AggregateException ex)
            {
                // this should throw, because last configuration retrived was null
                Assert.Throws <AggregateException>(() => configuration = configManager.GetConfigurationAsync().Result);

                ex.Handle((x) =>
                {
                    ee.ProcessException(x, context);
                    return(true);
                });
            }

            // get configuration with unsuccessful HTTP response status code
            configManager = new ConfigurationManager <OpenIdConnectConfiguration>("https://httpstat.us/429", new OpenIdConnectConfigurationRetriever());
            ee            = new ExpectedException(typeof(InvalidOperationException), "IDX20803:", typeof(IOException));
            try
            {
                configuration = configManager.GetConfigurationAsync().Result;
                ee.ProcessNoException(context);
            }
            catch (AggregateException ex)
            {
                // this should throw, because last configuration retrived was null
                Assert.Throws <AggregateException>(() => configuration = configManager.GetConfigurationAsync().Result);

                ex.Handle((x) =>
                {
                    ee.ProcessException(x, context);
                    return(true);
                });
            }

            // Unable to obtain a new configuration, but _currentConfiguration is not null so it should be returned.
            configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever);
            configuration = configManager.GetConfigurationAsync().Result;
            TestUtilities.SetField(configManager, "_lastRefresh", DateTimeOffset.UtcNow - TimeSpan.FromHours(1));
            configManager.RequestRefresh();
            TestUtilities.SetField(configManager, "_metadataAddress", "http://someaddress.com");
            configuration2 = configManager.GetConfigurationAsync().Result;
            IdentityComparer.AreEqual(configuration, configuration2, context);
            if (!object.ReferenceEquals(configuration, configuration2))
            {
                context.Diffs.Add("!object.ReferenceEquals(configuration, configuration2)");
            }

            TestUtilities.AssertFailIfErrors(context);
        }
        public void EmbeddedTokenConstructor1(string testId, JwtSecurityTokenTestVariation outerTokenVariation, JwtSecurityTokenTestVariation innerTokenVariation, string jwt, ExpectedException ee)
        {
            JwtSecurityToken outerJwt = null;
            JwtSecurityToken innerJwt = null;

            // create inner token
            try
            {
                if (innerTokenVariation != null)
                {
                    innerJwt = CreateToken(innerTokenVariation);
                }
            }
            catch (Exception ex)
            {
                ee.ProcessException(ex);
            }

            // create outer token
            try
            {
                if (string.IsNullOrEmpty(jwt))
                {
                    outerJwt = new JwtSecurityToken(
                        header: outerTokenVariation.Header,
                        innerToken: innerJwt,
                        rawHeader: outerTokenVariation.RawHeader,
                        rawEncryptedKey: outerTokenVariation.RawEncryptedKey,
                        rawInitializationVector: outerTokenVariation.RawInitializationVector,
                        rawCiphertext: outerTokenVariation.RawCiphertext,
                        rawAuthenticationTag: outerTokenVariation.RawAuthenticationTag);
                }
                else
                {
                    outerJwt = new JwtSecurityToken(jwt);
                }

                ee.ProcessNoException();
            }
            catch (Exception ex)
            {
                ee.ProcessException(ex);
            }

            try
            {
                // ensure we can get to every outer token property
                if (outerJwt != null && (ee == null || ee.TypeExpected == null))
                {
                    TestUtilities.CallAllPublicInstanceAndStaticPropertyGets(outerJwt, testId);
                }

                if (null != outerTokenVariation.ExpectedJwtSecurityToken)
                {
                    Assert.True(IdentityComparer.AreEqual(outerTokenVariation.ExpectedJwtSecurityToken, outerJwt));
                }
            }
            catch (Exception ex)
            {
                Assert.True(false, string.Format("Testcase: {0}. UnExpected when getting a properties: '{1}'", outerTokenVariation.Name, ex.ToString()));
            }

            try
            {
                // ensure we can get to every inner token property
                if (innerJwt != null && (ee == null || ee.TypeExpected == null))
                {
                    TestUtilities.CallAllPublicInstanceAndStaticPropertyGets(innerJwt, testId);
                }

                if (null != innerTokenVariation && null != innerTokenVariation.ExpectedJwtSecurityToken)
                {
                    Assert.True(IdentityComparer.AreEqual(innerTokenVariation.ExpectedJwtSecurityToken, innerJwt));
                }
            }
            catch (Exception ex)
            {
                Assert.True(false, string.Format("Testcase: {0}. UnExpected when getting a properties: '{1}'", testId, ex.ToString()));
            }

            try
            {
                if (outerJwt != null && innerJwt != null && (ee == null || ee.TypeExpected == null))
                {
                    // confirm properties of outer token match our expectation
                    Assert.Equal(outerJwt.InnerToken, innerJwt);
                    CheckPayloadProperties(outerJwt, innerJwt);
                    CheckOuterTokenProperties(outerJwt, outerTokenVariation);
                }
            }
            catch (Exception ex)
            {
                Assert.True(false, string.Format("Testcase: {0}. Unexpected inequality between outer and inner token properties: '{1}'", testId, ex.ToString()));
            }
        }