private void RunOpenIdConnectConfigurationTest(object obj, OpenIdConnectConfiguration compareTo, ExpectedException expectedException, CompareContext context, bool asString = true)
        {
            bool exceptionHit = false;

            OpenIdConnectConfiguration openIdConnectConfiguration = null;

            try
            {
                if (obj is string || asString)
                {
                    openIdConnectConfiguration = new OpenIdConnectConfiguration(obj as string);
                }

                expectedException.ProcessNoException(context.Diffs);
            }
            catch (Exception ex)
            {
                exceptionHit = true;
                expectedException.ProcessException(ex, context.Diffs);
            }

            if (!exceptionHit && compareTo != null)
            {
                IdentityComparer.AreEqual(openIdConnectConfiguration, compareTo, context);
            }
        }
示例#2
0
        private void RunEncodingVariation(List <Claim> claims, Dictionary <string, object> values, CompareContext context)
        {
            var jwtPayload1 = new JwtPayload(claims);
            var jwtPayload2 = new JwtPayload();

            foreach (var kv in values)
            {
                jwtPayload2[kv.Key] = kv.Value;
            }

            IdentityComparer.AreEqual(jwtPayload1, jwtPayload2, context);

            jwtPayload1 = JwtPayload.Base64UrlDeserialize(jwtPayload1.Base64UrlEncode());
            jwtPayload2 = JwtPayload.Base64UrlDeserialize(jwtPayload2.Base64UrlEncode());
            IdentityComparer.AreEqual(jwtPayload1, jwtPayload2, context);
        }
        public void GetSets()
        {
            OpenIdConnectConfiguration configuration = new OpenIdConnectConfiguration();
            Type type = typeof(OpenIdConnectConfiguration);

            PropertyInfo[] properties = type.GetProperties();
            if (properties.Length != 42)
            {
                Assert.True(false, "Number of properties has changed from 42 to: " + properties.Length + ", adjust tests");
            }

            TestUtilities.CallAllPublicInstanceAndStaticPropertyGets(configuration, "OpenIdConnectConfiguration_GetSets");

            GetSetContext context =
                new GetSetContext
            {
                PropertyNamesAndSetGetValue = new List <KeyValuePair <string, List <object> > >
                {
                    new KeyValuePair <string, List <object> >("AuthorizationEndpoint", new List <object> {
                        (string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()
                    }),
                    new KeyValuePair <string, List <object> >("CheckSessionIframe", new List <object> {
                        (string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()
                    }),
                    new KeyValuePair <string, List <object> >("ClaimsParameterSupported", new List <object> {
                        false, true, false
                    }),
                    new KeyValuePair <string, List <object> >("EndSessionEndpoint", new List <object> {
                        (string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()
                    }),
                    new KeyValuePair <string, List <object> >("HttpLogoutSupported", new List <object> {
                        false, true, true
                    }),
                    new KeyValuePair <string, List <object> >("Issuer", new List <object> {
                        (string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()
                    }),
                    new KeyValuePair <string, List <object> >("JwksUri", new List <object> {
                        (string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()
                    }),
                    new KeyValuePair <string, List <object> >("JsonWebKeySet", new List <object> {
                        null, new JsonWebKeySet()
                    }),
                    new KeyValuePair <string, List <object> >("LogoutSessionSupported", new List <object> {
                        false, true, true
                    }),
                    new KeyValuePair <string, List <object> >("OpPolicyUri", new List <object> {
                        (string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()
                    }),
                    new KeyValuePair <string, List <object> >("OpTosUri", new List <object> {
                        (string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()
                    }),
                    new KeyValuePair <string, List <object> >("RegistrationEndpoint", new List <object> {
                        (string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()
                    }),
                    new KeyValuePair <string, List <object> >("RequireRequestUriRegistration", new List <object> {
                        false, true, true
                    }),
                    new KeyValuePair <string, List <object> >("RequestParameterSupported", new List <object> {
                        false, true, false
                    }),
                    new KeyValuePair <string, List <object> >("RequestUriParameterSupported", new List <object> {
                        false, true, true
                    }),
                    new KeyValuePair <string, List <object> >("ServiceDocumentation", new List <object> {
                        (string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()
                    }),
                    new KeyValuePair <string, List <object> >("TokenEndpoint", new List <object> {
                        (string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()
                    }),
                    new KeyValuePair <string, List <object> >("UserInfoEndpoint", new List <object> {
                        (string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()
                    }),
                },

                Object = configuration,
            };

            TestUtilities.GetSet(context);
            TestUtilities.AssertFailIfErrors("OpenIdConnectConfiguration_GetSets", context.Errors);

            string authorization_Endpoint = Guid.NewGuid().ToString();
            string end_Session_Endpoint   = Guid.NewGuid().ToString();
            string issuer         = Guid.NewGuid().ToString();
            string jwks_Uri       = Guid.NewGuid().ToString();
            string token_Endpoint = Guid.NewGuid().ToString();

            configuration = new OpenIdConnectConfiguration()
            {
                AuthorizationEndpoint = authorization_Endpoint,
                EndSessionEndpoint    = end_Session_Endpoint,
                Issuer        = issuer,
                JwksUri       = jwks_Uri,
                TokenEndpoint = token_Endpoint,
            };

            List <SecurityKey> securityKeys = new List <SecurityKey> {
                new X509SecurityKey(KeyingMaterial.Cert_1024), new X509SecurityKey(KeyingMaterial.DefaultCert_2048)
            };

            configuration.SigningKeys.Add(new X509SecurityKey(KeyingMaterial.Cert_1024));
            configuration.SigningKeys.Add(new X509SecurityKey(KeyingMaterial.DefaultCert_2048));

            List <string> errors = new List <string>();

            if (!string.Equals(configuration.AuthorizationEndpoint, authorization_Endpoint))
            {
                errors.Add(string.Format(CultureInfo.InvariantCulture, "configuration.AuthorizationEndpoint != authorization_Endpoint. '{0}', '{1}'.", configuration.AuthorizationEndpoint, authorization_Endpoint));
            }

            if (!string.Equals(configuration.EndSessionEndpoint, end_Session_Endpoint))
            {
                errors.Add(string.Format(CultureInfo.InvariantCulture, "configuration.EndSessionEndpoint != end_Session_Endpoint. '{0}', '{1}'.", configuration.EndSessionEndpoint, end_Session_Endpoint));
            }

            if (!string.Equals(configuration.Issuer, issuer))
            {
                errors.Add(string.Format(CultureInfo.InvariantCulture, "configuration.Issuer != issuer. '{0}', '{1}'.", configuration.Issuer, issuer));
            }

            if (!string.Equals(configuration.JwksUri, jwks_Uri))
            {
                errors.Add(string.Format(CultureInfo.InvariantCulture, "configuration.JwksUri != jwks_Uri. '{0}', '{1}'.", configuration.JwksUri, jwks_Uri));
            }

            if (!string.Equals(configuration.TokenEndpoint, token_Endpoint))
            {
                errors.Add(string.Format(CultureInfo.InvariantCulture, "configuration.TokenEndpoint != token_Endpoint. '{0}', '{1}'.", configuration.TokenEndpoint, token_Endpoint));
            }

            CompareContext compareContext = new CompareContext();

            if (!IdentityComparer.AreEqual(configuration.SigningKeys, securityKeys, compareContext))
            {
                errors.AddRange(compareContext.Diffs);
            }

            TestUtilities.AssertFailIfErrors("OpenIdConnectConfiguration_GetSets", errors);
        }
示例#4
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);
                });
            }

            TestUtilities.AssertFailIfErrors(context);
        }
示例#5
0
        private void CheckClaimsTypeParsing(IEnumerable <Claim> claims, CompareContext context)
        {
            if (claims == null)
            {
                return;
            }

            foreach (var claim in claims)
            {
                switch (claim.ValueType)
                {
                case ClaimValueTypes.Boolean:
                    bool boolRet;
                    if (!bool.TryParse(claim.Value, out boolRet))
                    {
                        context.Diffs.Add(string.Format(CultureInfo.InvariantCulture, "bool.TryParse(claim.Value, out boolRet), value: '{0}'", claim.Value));
                    }

                    break;

                case ClaimValueTypes.Double:
                    double doubleRet;
                    if (!double.TryParse(claim.Value, out doubleRet))
                    {
                        context.Diffs.Add(string.Format(CultureInfo.InvariantCulture, "double.TryParse(claim.Value, out doubleRet), value: '{0}'", claim.Value));
                    }

                    break;

                case ClaimValueTypes.Integer:
                    int intRet;
                    if (!int.TryParse(claim.Value, out intRet))
                    {
                        context.Diffs.Add(string.Format(CultureInfo.InvariantCulture, "int.TryParse(claim.Value, out intRet), value: '{0}'", claim.Value));
                    }

                    break;

                case ClaimValueTypes.Integer32:
                    int intRet32;
                    if (!int.TryParse(claim.Value, out intRet32))
                    {
                        context.Diffs.Add(string.Format(CultureInfo.InvariantCulture, "int.TryParse(claim.Value, out intRet32), value: '{0}'", claim.Value));
                    }

                    break;

                case ClaimValueTypes.Integer64:
                    long long64;
                    if (!long.TryParse(claim.Value, out long64))
                    {
                        context.Diffs.Add(string.Format(CultureInfo.InvariantCulture, "long.TryParse(claim.Value, out long64), value: '{0}'", claim.Value));
                    }

                    break;

                case JsonClaimValueTypes.Json:
                    try
                    {
                        JObject.Parse(claim.Value);
                    }
                    catch (Exception ex)
                    {
                        context.Diffs.Add(string.Format(CultureInfo.InvariantCulture, "JObject.Parse(claim.Value) threw: '{0}', value: '{1}'", ex, claim.Value));
                    }

                    break;

                case JsonClaimValueTypes.JsonArray:
                    try
                    {
                        JArray.Parse(claim.Value);
                    }
                    catch (Exception ex)
                    {
                        context.Diffs.Add(string.Format(CultureInfo.InvariantCulture, "JArray.Parse(claim.Value) threw: '{0}', value: '{1}'", ex, claim.Value));
                    }
                    break;
                }
            }
        }
示例#6
0
        public void GetPayloadValues()
        {
            var context = new CompareContext();

            TestUtilities.WriteHeader($"{this}.GetPayloadValues");

            var token = new JsonWebToken("{}", jObject);

            var intarray = token.GetPayloadValue <int[]>("intarray");

            IdentityComparer.AreEqual(new int[] { 1, 2, 3 }, intarray, context);

            var array = token.GetPayloadValue <object[]>("array");

            IdentityComparer.AreEqual(new object[] { 1L, "2", 3L }, array, context);

            // only possible internally within the library since we're using Microsoft.IdentityModel.Json.Linq.JObject
            var jobject = token.GetPayloadValue <JObject>("jobject");

            IdentityComparer.AreEqual(JObject.Parse(@"{ ""string1"":""string1value"", ""string2"":""string2value"" }"), jobject, context);

            var name = token.GetPayloadValue <string>("string");

            IdentityComparer.AreEqual("bob", name, context);

            var floatingPoint = token.GetPayloadValue <float>("float");

            IdentityComparer.AreEqual(42.0, floatingPoint, context);

            var integer = token.GetPayloadValue <int>("integer");

            IdentityComparer.AreEqual(42, integer, context);

            var nill = token.GetPayloadValue <object>("nill");

            IdentityComparer.AreEqual(nill, null, context);

            var boolean = token.GetPayloadValue <bool>("bool");

            IdentityComparer.AreEqual(boolean, true, context);

            var dateTimeValue = token.GetPayloadValue <string>("dateTime");

            IdentityComparer.AreEqual(dateTimeValue, dateTime.ToString(), context);

            var dateTimeIso8061Value = token.GetPayloadValue <DateTime>("dateTimeIso8061");

            IdentityComparer.AreEqual(dateTimeIso8061Value, dateTime, context);

            try // Try to retrieve a value that doesn't exist in the header.
            {
                token.GetPayloadValue <int>("doesnotexist");
            }
            catch (Exception ex)
            {
                ExpectedException.ArgumentException("IDX14304:").ProcessException(ex, context);
            }

            try // Try to retrieve an integer when the value is actually a string.
            {
                token.GetPayloadValue <int>("string");
            }
            catch (Exception ex)
            {
                ExpectedException.ArgumentException("IDX14305:", typeof(System.FormatException)).ProcessException(ex, context);
            }

            TestUtilities.AssertFailIfErrors(context);
        }
示例#7
0
        public void TryGetPayloadValues()
        {
            var context = new CompareContext();

            TestUtilities.WriteHeader($"{this}.TryGetPayloadValues");

            var token = new JsonWebToken("{}", jObject);

            var success = token.TryGetPayloadValue("intarray", out int[] intarray);

            IdentityComparer.AreEqual(new int[] { 1, 2, 3 }, intarray, context);
            IdentityComparer.AreEqual(true, success, context);

            success = token.TryGetPayloadValue("array", out object[] array);
            IdentityComparer.AreEqual(new object[] { 1L, "2", 3L }, array, context);
            IdentityComparer.AreEqual(true, success, context);

            // only possible internally within the library since we're using Microsoft.IdentityModel.Json.Linq.JObject
            success = token.TryGetPayloadValue("jobject", out JObject jobject);
            IdentityComparer.AreEqual(JObject.Parse(@"{ ""string1"":""string1value"", ""string2"":""string2value"" }"), jobject, context);
            IdentityComparer.AreEqual(true, success, context);

            success = token.TryGetPayloadValue("string", out string name);
            IdentityComparer.AreEqual("bob", name, context);
            IdentityComparer.AreEqual(true, success, context);

            success = token.TryGetPayloadValue("float", out float floatingPoint);
            IdentityComparer.AreEqual(42.0, floatingPoint, context);
            IdentityComparer.AreEqual(true, success, context);

            success = token.TryGetPayloadValue("integer", out int integer);
            IdentityComparer.AreEqual(42, integer, context);
            IdentityComparer.AreEqual(true, success, context);

            success = token.TryGetPayloadValue("nill", out object nill);
            IdentityComparer.AreEqual(nill, null, context);
            IdentityComparer.AreEqual(true, success, context);

            success = token.TryGetPayloadValue("bool", out bool boolean);
            IdentityComparer.AreEqual(boolean, true, context);
            IdentityComparer.AreEqual(true, success, context);

            var dateTimeValue = token.GetPayloadValue <string>("dateTime");

            IdentityComparer.AreEqual(dateTimeValue, dateTime.ToString(), context);
            IdentityComparer.AreEqual(true, success, context);

            var dateTimeIso8061Value = token.GetPayloadValue <DateTime>("dateTimeIso8061");

            IdentityComparer.AreEqual(dateTimeIso8061Value, dateTime, context);
            IdentityComparer.AreEqual(true, success, context);

            success = token.TryGetPayloadValue("doesnotexist", out int doesNotExist);
            IdentityComparer.AreEqual(0, doesNotExist, context);
            IdentityComparer.AreEqual(false, success, context);

            success = token.TryGetPayloadValue("string", out int cannotConvert);
            IdentityComparer.AreEqual(0, cannotConvert, context);
            IdentityComparer.AreEqual(false, success, context);

            TestUtilities.AssertFailIfErrors(context);
        }
        public void CreateAndValidateTokens_RoleClaims()
        {
            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
            TokenValidationParameters validationParameters = new TokenValidationParameters
            {
                IssuerSigningToken = KeyingMaterial.DefaultX509Token_2048,
                ValidateAudience = false,
                ValidateIssuer = false,
            };

            string issuer = "https://gotjwt.com";
            DateTime utcNow = DateTime.UtcNow;
            DateTime expire = utcNow + TimeSpan.FromHours(1);
            ClaimsIdentity subject = new ClaimsIdentity(claims: ClaimSets.RoleClaimsShortType(issuer, issuer));
            JwtSecurityToken jwtToken = handler.CreateToken(issuer: issuer, signingCredentials: KeyingMaterial.DefaultX509SigningCreds_2048_RsaSha2_Sha2, subject: subject) as JwtSecurityToken;

            SecurityToken securityToken;
            ClaimsPrincipal principal = handler.ValidateToken(jwtToken.RawData, validationParameters, out securityToken);
            CheckForRoles(new string[] {"role1", "roles1" }, new string[] { "notrole1", "notrole2" }, principal);

            ClaimsIdentity expectedIdentity =
                new ClaimsIdentity(
                    authenticationType: "Federation",
                    claims: ClaimSets.RoleClaimsLongType(issuer, issuer)
                    );

            Claim claim = new Claim(type: JwtRegisteredClaimNames.Iss, value: issuer, valueType: ClaimValueTypes.String, issuer: issuer);
            expectedIdentity.AddClaim(claim);

            claim = new Claim(JwtRegisteredClaimNames.Exp, EpochTime.GetIntDate(expire).ToString(), valueType: "JSON", issuer: issuer);
            claim.Properties.Add(JwtSecurityTokenHandler.JsonClaimTypeProperty, "System.Int32");
            expectedIdentity.AddClaim(claim);

            claim = new Claim(JwtRegisteredClaimNames.Nbf, EpochTime.GetIntDate(utcNow).ToString(), valueType: "JSON", issuer: issuer);
            claim.Properties.Add(JwtSecurityTokenHandler.JsonClaimTypeProperty, "System.Int32");
            expectedIdentity.AddClaim(claim);

            CompareContext context = new CompareContext();
            IdentityComparer.AreEqual<IEnumerable<Claim>>(principal.Claims, expectedIdentity.Claims, context);
            Assert.IsTrue(context.Errors.Count == 0);
        }
        public void CreateAndValidateTokens_MultipleAudiences()
        {
            List<string> errors = new List<string>();

            var handler = new JwtSecurityTokenHandler();
            var payload = new JwtPayload();
            var header = new JwtHeader();

            payload.AddClaims(ClaimSets.MultipleAudiences(IdentityUtilities.DefaultIssuer, IdentityUtilities.DefaultIssuer));
            var jwtToken = new JwtSecurityToken(header, payload);
            var jwt = handler.WriteToken(jwtToken);

            var validationParameters =
                new TokenValidationParameters
                {
                    RequireExpirationTime = false,
                    RequireSignedTokens = false,
                    ValidateAudience = false,
                    ValidateIssuer = false,
                    ValidateLifetime = false,
                };

            SecurityToken validatedJwt = null;
            var cp = handler.ValidateToken(jwt, validationParameters, out validatedJwt);
            var ci = new ClaimsIdentity(ClaimSets.MultipleAudiences(IdentityUtilities.DefaultIssuer, IdentityUtilities.DefaultIssuer), AuthenticationTypes.Federation);
            var cpExpected = new ClaimsPrincipal(ci);
            var compareContext = new CompareContext();
            if (!IdentityComparer.AreEqual<ClaimsPrincipal>(cp, cpExpected, compareContext))
            {
                errors.Add("IdentityComparer.AreEqual<ClaimsPrincipal>(cp, cpExpected, compareContext)");
            }

            var audiences = (validatedJwt as JwtSecurityToken).Audiences;
            var jwtAudiences = jwtToken.Audiences;

            if (!IdentityComparer.AreEqual<IEnumerable<string>>(audiences, jwtAudiences))
            {
                errors.Add("!IdentityComparer.AreEqual<IEnumerable<string>>(audiences, jwtAudiences)");
            }

            if (!IdentityComparer.AreEqual<IEnumerable<string>>(audiences, IdentityUtilities.DefaultAudiences))
            {
                errors.Add("!IdentityComparer.AreEqual<IEnumerable<string>>(audiences, IdentityUtilities.DefaultAudiences)");
            }

            TestUtilities.AssertFailIfErrors(MethodInfo.GetCurrentMethod().Name, errors);
        }
        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;

            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);
            configManager.RequestRefresh();
            configuration = configManager.GetConfigurationAsync().Result;
            TestUtilities.SetField(configManager, "_lastRefresh", DateTimeOffset.UtcNow - TimeSpan.FromHours(1));
            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;
            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)");
            }

            configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever);
            configuration = configManager.GetConfigurationAsync().Result;
            // First force refresh should pickup new config
            configManager.RequestRefresh();
            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) (4)");
            }
            // Next force refresh shouldn't pickup new config, as RefreshInterval hasn't passed
            configManager.RequestRefresh();
            configManager.MetadataAddress = "OpenIdConnectMetadata.json";
            var configuration3 = configManager.GetConfigurationAsync().Result;

            IdentityComparer.AreEqual(configuration2, configuration3, context);
            if (!object.ReferenceEquals(configuration2, configuration3))
            {
                context.Diffs.Add("!object.ReferenceEquals(configuration2, configuration3) (5)");
            }
            // Next force refresh should pickup config since, RefreshInterval is set to 1s
            configManager.RefreshInterval = TimeSpan.FromSeconds(1);
            Thread.Sleep(1000);
            configManager.RequestRefresh();
            var configuration4 = configManager.GetConfigurationAsync().Result;

            if (IdentityComparer.AreEqual(configuration2, configuration4))
            {
                context.Diffs.Add("IdentityComparer.AreEqual(configuration2, configuration4), should be different");
            }
            if (object.ReferenceEquals(configuration2, configuration4))
            {
                context.Diffs.Add("object.ReferenceEquals(configuration2, configuration4) (6)");
            }

            // 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();
            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();
            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);
        }
        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);
        }
示例#12
0
        public static void Main(string[] args)
        {
            string myassembly = Assembly.GetExecutingAssembly().Location;

            monoroot    = new FileInfo(myassembly).Directory.Parent.Parent.Parent.Parent.FullName;
            monolibmono = monoroot + "/../Mono/builds/monodistribution/lib/mono/";

            string originalprofiledirectory = UnityProfilesUtils.DirectoryNameFromProfile(UnityProfiles.None);
            Dictionary <UnityProfiles, UnityProfilesDocumentation> docs = new Dictionary <UnityProfiles, UnityProfilesDocumentation> ();
            UnityProfilesDocumentation mergedDoc = new UnityProfilesDocumentation();

            Dictionary <string, MasterAssembly> masterInfos = new Dictionary <string, MasterAssembly> ();

            foreach (var file in Directory.GetFiles(monolibmono + originalprofiledirectory, "*.dll"))
            {
                if (!file.Contains("mscorlib") && !file.Contains("System."))
                {
                    continue;
                }
                // FIXME: for some reason, mono-api-info.exe fails on these assemblies (Cecil failure).
                if (file.Contains("System.Web.DynamicData.dll"))
                {
                    continue;
                }
                if (file.Contains("System.Web.Extensions.dll"))
                {
                    continue;
                }
                if (file.Contains("System.Web.Routing.dll"))
                {
                    continue;
                }
                if (file.Contains("System.Web.dll"))
                {
                    continue;
                }

                string assemblyname = Path.GetFileName(file);
                Console.WriteLine("Reading reference assembly {0}", assemblyname);

                string         originalxml = GenerateAPIInfo(file);
                MasterAssembly reference   = new MasterAssembly(originalxml);
                masterInfos [assemblyname] = reference;
            }

            foreach (UnityProfiles profile in UnityProfilesUtils.ListProfiles())
            {
                var newprofiledirectory = profile.DirectoryNameFromProfile();

                Console.WriteLine(" *** Working on profile {0} (directory {1})", profile, newprofiledirectory);

                foreach (var file in Directory.GetFiles(monolibmono + newprofiledirectory, "*.dll"))
                {
                    if (!file.Contains("mscorlib") && !file.Contains("System."))
                    {
                        continue;
                    }
                    // FIXME: for some reason, mono-api-info.exe fails on these assemblies (Cecil failure).
                    if (file.Contains("System.Web.DynamicData.dll"))
                    {
                        continue;
                    }
                    if (file.Contains("System.Web.Extensions.dll"))
                    {
                        continue;
                    }
                    if (file.Contains("System.Web.Routing.dll"))
                    {
                        continue;
                    }
                    if (file.Contains("System.Web.dll"))
                    {
                        continue;
                    }

                    string assemblyname = Path.GetFileName(file);
                    Console.WriteLine("Working on assembly {0}", assemblyname);

                    if (!masterInfos.ContainsKey(assemblyname))
                    {
                        Console.WriteLine("Assembly {0} from profile {1} not found in main master infos, skipping", assemblyname, profile);
                        continue;
                    }

                    Console.WriteLine("Reading assembly {0} in profile {1}", assemblyname, profile);
                    string newxml = GenerateAPIInfo(file);
                    GuiCompare.MasterAssembly target = new MasterAssembly(newxml);

                    GuiCompare.MasterAssembly  reference = masterInfos [assemblyname];
                    UnityProfilesDocumentation currentProfileDocumentation = new UnityProfilesDocumentation();
                    docs [profile] = currentProfileDocumentation;

                    CompareContext comparer = new CompareContext(() => reference, () => target, profile, currentProfileDocumentation);
                    //CompareContext comparer = new CompareContext(() => reference,() => target, profile, doc);

                    bool finished = false;
                    comparer.Finished        += (a, b) => finished = true;
                    comparer.ProgressChanged += (a, b) => Console.WriteLine(b.ToString());
                    comparer.Compare();
                    while (!finished)
                    {
                        Console.WriteLine("Waiting for comparison to finish...");
                        Thread.Sleep(2000);
                    }

                    // Handle errors here...
                }
            }

            // Merge profiles
            foreach (UnityProfiles profile in UnityProfilesUtils.ListProfiles())
            {
                Console.WriteLine(" *** Merging profile {0}", profile);
                UnityProfilesDocumentation currentDoc = docs [profile];
                foreach (DocumentedNamespace ns in currentDoc.Namespaces)
                {
                    DocumentedNamespace referenceNs = mergedDoc.AddReferenceNamespace(ns.Name);
                    foreach (DocumentedClass c in ns.Classes)
                    {
                        DocumentedClass referenceClass = referenceNs.AddReferenceClass(c.Name);
                        referenceClass.AddSupportedProfile(profile);
                        foreach (DocumentedMember member in c.Members)
                        {
                            DocumentedMember referenceMember;
                            if (member is DocumentedField)
                            {
                                referenceMember = referenceClass.AddReferenceField(member.Name);
                            }
                            else if (member is DocumentedProperty)
                            {
                                referenceMember = referenceClass.AddReferenceProperty(member.Name);
                            }
                            else if (member is DocumentedMethod)
                            {
                                referenceMember = referenceClass.AddReferenceMethod(member.Name);
                            }
                            else
                            {
                                referenceMember = null;
                            }
                            referenceMember.AddSupportedProfile(profile);
                        }
                    }
                }
            }

            // Generate report here...
            Console.WriteLine(" *** Dumping merged docs");
            //mergedDoc.DebugDump ();
        }