Esempio n. 1
0
        public void RoundTripJWEKeyWrapping(CreateTokenTheoryData theoryData)
        {
            var context                 = TestUtilities.WriteHeader($"{this}.RoundTripJWE", theoryData);
            var jsonWebTokenHandler     = new JsonWebTokenHandler();
            var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
            var jweCreatedInMemory      = jsonWebTokenHandler.CreateToken(theoryData.Payload, theoryData.SigningCredentials, theoryData.EncryptingCredentials);
            var jweCreatedInMemoryToken = new JsonWebToken(jweCreatedInMemory);

            try
            {
                var tokenValidationResult = jsonWebTokenHandler.ValidateToken(jweCreatedInMemory, theoryData.ValidationParameters);
                var outerToken            = tokenValidationResult.SecurityToken as JsonWebToken;
                jwtSecurityTokenHandler.ValidateToken(jweCreatedInMemory, theoryData.ValidationParameters, out SecurityToken validatedTokenFromJwtHandler);

                IdentityComparer.AreEqual((validatedTokenFromJwtHandler as JwtSecurityToken).Claims, outerToken.Claims, context);

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

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

                context.PropertiesToIgnoreWhenComparing = new Dictionary <Type, List <string> >
                {
                    { typeof(JsonWebToken), new List <string> {
                          "EncodedToken"
                      } },
                };

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

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

                TestUtilities.AssertFailIfErrors(string.Format(CultureInfo.InvariantCulture, "RoundTripJWE: "), context.Diffs);
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }
        }
        public void JsonWebKey_GetSets()
        {
            JsonWebKey jsonWebKey = new JsonWebKey();

            TestUtilities.CallAllPublicInstanceAndStaticPropertyGets(jsonWebKey, "JsonWebKey_GetSets");
            List <string> methods = new List <string> {
                "Alg", "KeyOps", "Kid", "Kty", "X5t", "X5u", "Use"
            };

            foreach (string method in methods)
            {
                TestUtilities.GetSet(jsonWebKey, method, null, new object[] { Guid.NewGuid().ToString(), null, Guid.NewGuid().ToString() });
                jsonWebKey.X5c.Add(method);
            }

            Assert.IsTrue(IdentityComparer.AreEqual <IEnumerable <string> >(jsonWebKey.X5c, methods, CompareContext.Default));
        }
        private void GetSigningTokens(string webKeySetString, List <SecurityToken> expectedTokens, ExpectedException expectedException)
        {
            JsonWebKeySet webKeySet = new JsonWebKeySet(webKeySetString);

            try
            {
                IList <SecurityToken> tokens = webKeySet.GetSigningTokens();
                expectedException.ProcessNoException();
                if (expectedTokens != null)
                {
                    Assert.IsTrue(IdentityComparer.AreEqual <IEnumerable <SecurityToken> >(tokens, expectedTokens));
                }
            }
            catch (Exception ex)
            {
                expectedException.ProcessException(ex);
            }
        }
        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;
        }
Esempio n. 5
0
        public void Validate_NullOrEmptyParameters_ThrowsException()
        {
            var context          = new CompareContext();
            var validator        = new AadIssuerValidator(_httpClient, ValidatorConstants.AadIssuer);
            var jwtSecurityToken = new JwtSecurityToken();
            var validationParams = new TokenValidationParameters();

            Assert.Throws <ArgumentNullException>(ValidatorConstants.Issuer, () => validator.Validate(null, jwtSecurityToken, validationParams));

            var exception = Assert.Throws <SecurityTokenInvalidIssuerException>(() => validator.Validate(string.Empty, jwtSecurityToken, validationParams));

            IdentityComparer.AreEqual(LogMessages.IDX40003, exception.Message);

            Assert.Throws <ArgumentNullException>(ValidatorConstants.SecurityToken, () => validator.Validate(ValidatorConstants.AadIssuer, null, validationParams));

            Assert.Throws <ArgumentNullException>(ValidatorConstants.ValidationParameters, () => validator.Validate(ValidatorConstants.AadIssuer, jwtSecurityToken, null));
            TestUtilities.AssertFailIfErrors(context);
        }
Esempio n. 6
0
        public void ReadReference(DSigSerializerTheoryData theoryData)
        {
            TestUtilities.WriteHeader($"{this}.ReadReference", theoryData);
            var context = new CompareContext($"{this}.ReadReference, {theoryData.TestId}");

            try
            {
                var reference = theoryData.Serializer.ReadReference(XmlUtilities.CreateDictionaryReader(theoryData.Xml));
                theoryData.ExpectedException.ProcessNoException(context);
                IdentityComparer.AreEqual(reference, theoryData.Reference, context);
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }

            TestUtilities.AssertFailIfErrors(context);
        }
Esempio n. 7
0
        public void CompareTokenValidationParameters()
        {
            TestUtilities.WriteHeader($"{this}.CompareTokenValidationParameters", true);
            var context = new CompareContext($"{this}.CompareTokenValidationParameters");
            var tokenValidationParameters1 =
                new TokenValidationParameters {
                AuthenticationType = Guid.NewGuid().ToString()
            };
            var tokenValidationParameters2 =
                new TokenValidationParameters()
            {
                AuthenticationType = Guid.NewGuid().ToString()
            };

            IdentityComparer.AreEqual(tokenValidationParameters1, tokenValidationParameters2, context);

            Assert.True(context.Diffs.Count(s => s == "AuthenticationType:") == 1);
        }
Esempio n. 8
0
        public void OpenIdConnectConfiguration_GetSets()
        {
            OpenIdConnectConfiguration configuration = new OpenIdConnectConfiguration();

            TestUtilities.CallAllPublicInstanceAndStaticPropertyGets(configuration, "OpenIdConnectMetadata_GetSets");

            List <string> methods = new List <string> {
                "AuthorizationEndpoint", "EndSessionEndpoint", "Issuer", "JwksUri", "TokenEndpoint", "UserInfoEndpoint"
            };

            foreach (string method in methods)
            {
                TestUtilities.GetSet(configuration, method, null, new object[] { Guid.NewGuid().ToString(), null, Guid.NewGuid().ToString() });
            }

            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));

            Assert.AreEqual(configuration.AuthorizationEndpoint, authorization_Endpoint);
            Assert.AreEqual(configuration.EndSessionEndpoint, end_Session_Endpoint);
            Assert.AreEqual(configuration.Issuer, issuer);
            Assert.AreEqual(configuration.JwksUri, jwks_Uri);
            Assert.AreEqual(configuration.TokenEndpoint, token_Endpoint);
            Assert.IsTrue(IdentityComparer.AreEqual <IEnumerable <SecurityKey> >(configuration.SigningKeys, securityKeys));
        }
        /// <summary>
        /// Sets a property, then checks it, checking for an expected exception.
        /// </summary>
        /// <param name="obj">object that has a 'setter'.</param>
        /// <param name="property">the name of the property.</param>
        /// <param name="propertyValue">value to set on the property.</param>
        /// <param name="expectedException">checks that exception is correct.</param>
        public static void SetGet(object obj, string property, object propertyValue, ExpectedException expectedException, GetSetContext context)
        {
            if (obj == null)
            {
                throw new TestException("obj == null");
            }

            if (string.IsNullOrWhiteSpace(property))
            {
                throw new TestException("string.IsNullOrWhiteSpace(property)");
            }

            Type         type         = obj.GetType();
            PropertyInfo propertyInfo = type.GetProperty(property);

            if (propertyInfo == null)
            {
                context.Errors.Add("'get is not found for property: '" + property + "', type: '" + type.ToString() + "'");
                return;
            }

            if (!propertyInfo.CanWrite)
            {
                context.Errors.Add("can not write to property: '" + property + "', type: '" + type.ToString() + "'");
                return;
            }

            var compareContext = new CompareContext();

            try
            {
                propertyInfo.SetValue(obj, propertyValue);
                object retval = propertyInfo.GetValue(obj);
                IdentityComparer.AreEqual(propertyValue, retval, compareContext);
                expectedException.ProcessNoException(compareContext);
            }
            catch (Exception exception)
            {
                // look for InnerException as exception is a wrapped exception.
                expectedException.ProcessException(exception.InnerException, compareContext);
            }

            context.Errors.AddRange(compareContext.Diffs);
        }
Esempio n. 10
0
        public void ClaimSourceAndClaimName()
        {
            string claimSources = "_claim_sources";
            string claimNames   = "_claim_names";
            var    context      = new CompareContext();

            JwtPayload payload = new JwtPayload();

            payload.Add(claimSources, JsonClaims.ClaimSourcesAsDictionary);
            payload.Add(claimNames, JsonClaims.ClaimNamesAsDictionary);
            payload.Add("iss", IdentityUtilities.DefaultIssuer);

            JwtSecurityToken        jwtToken   = new JwtSecurityToken(new JwtHeader(), payload);
            JwtSecurityTokenHandler jwtHandler = new JwtSecurityTokenHandler();
            string encodedJwt           = jwtHandler.WriteToken(new JwtSecurityToken(new JwtHeader(), payload));
            var    validationParameters = new TokenValidationParameters
            {
                IssuerValidator     = (issuer, st, tvp) => { return(issuer); },
                RequireSignedTokens = false,
                ValidateAudience    = false,
                ValidateLifetime    = false,
            };

            SecurityToken validatedJwt     = null;
            var           claimsPrincipal  = jwtHandler.ValidateToken(encodedJwt, validationParameters, out validatedJwt);
            var           expectedIdentity = JsonClaims.ClaimsIdentityDistributedClaims(
                IdentityUtilities.DefaultIssuer,
                TokenValidationParameters.DefaultAuthenticationType,
                JsonClaims.ClaimSourcesAsDictionary,
                JsonClaims.ClaimNamesAsDictionary);

            IdentityComparer.AreEqual(claimsPrincipal.Identity as ClaimsIdentity, expectedIdentity, context);

            jwtToken   = new JwtSecurityToken(new JwtHeader(), new JwtPayload(IdentityUtilities.DefaultIssuer, null, ClaimSets.EntityAsJsonClaim(IdentityUtilities.DefaultIssuer, IdentityUtilities.DefaultIssuer), null, null));
            encodedJwt = jwtHandler.WriteToken(jwtToken);
            SecurityToken validatedToken;
            var           cp = jwtHandler.ValidateToken(encodedJwt, validationParameters, out validatedToken);

            IdentityComparer.AreEqual(
                cp.FindFirst(typeof(Entity).ToString()),
                new Claim(typeof(Entity).ToString(), JsonExtensions.SerializeToJson(Entity.Default), JsonClaimValueTypes.Json, IdentityUtilities.DefaultIssuer, IdentityUtilities.DefaultIssuer, cp.Identity as ClaimsIdentity),
                context);
            TestUtilities.AssertFailIfErrors(context.Diffs);
        }
        private void RunAudienceVariation(List <Claim> audienceClaims, List <string> expectedAudiences, CompareContext context)
        {
            var handler         = new JwtSecurityTokenHandler();
            var tokenDescriptor = IdentityUtilities.DefaultAsymmetricSecurityTokenDescriptor(audienceClaims);

            tokenDescriptor.Audience = null;
            var jwt = handler.CreateEncodedJwt(tokenDescriptor);

            SecurityToken token           = null;
            var           claimsPrincipal = handler.ValidateToken(jwt, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, out token);
            var           jwtToken        = token as JwtSecurityToken;
            var           audiences       = jwtToken.Audiences;

            IdentityComparer.AreEqual(audiences, expectedAudiences as IEnumerable <string>, context);

            ClaimsIdentity identity = claimsPrincipal.Identity as ClaimsIdentity;

            IdentityComparer.AreEqual(identity.FindAll(JwtRegisteredClaimNames.Aud), audienceClaims, context);
        }
Esempio n. 12
0
        public void Validate_IssuerMatchedInValidIssuer_ReturnsIssuer(string tidClaimType, string tenantId, string issuer)
        {
            var context   = new CompareContext();
            var validator = new AadIssuerValidator(_httpClient, issuer);
            var tidClaim  = new Claim(tidClaimType, tenantId);

            var issClaim         = new Claim(ValidatorConstants.ClaimNameIss, issuer);
            var jwtSecurityToken = new JwtSecurityToken(issuer: issuer, claims: new[] { issClaim, tidClaim });

            validator.AadIssuerV2 = issuer;

            var actualIssuer = validator.Validate(issuer, jwtSecurityToken, new TokenValidationParameters()
            {
                ValidIssuer = issuer
            });

            IdentityComparer.AreEqual(issuer, actualIssuer, context);
            TestUtilities.AssertFailIfErrors(context);
        }
Esempio n. 13
0
        public void Constructors()
        {
            var header1 = new JwtHeader();
            SigningCredentials signingCredentials = null;
            var header2 = new JwtHeader(signingCredentials);

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

            IdentityComparer.AreEqual(header1, header2, context);
            TestUtilities.AssertFailIfErrors("JwtHeaderTests.Constructors", context.Diffs);
        }
Esempio n. 14
0
        public void CompareSamlAssertions()
        {
            TestUtilities.WriteHeader($"{this}.CompareSamlAssertions", true);
            var context        = new CompareContext($"{this}.CompareSamlAssertions");
            var samlAssertion1 = new SamlAssertion(Guid.NewGuid().ToString(), Default.Issuer, DateTime.Parse(Default.IssueInstantString), null, new SamlAdvice(), new List <SamlStatement> {
                new SamlAttributeStatement(new SamlSubject(), new List <SamlAttribute> {
                    new SamlAttribute("1", "2", "3")
                })
            });
            var samlAssertion2 = new SamlAssertion(Guid.NewGuid().ToString(), Default.Issuer, DateTime.Parse(Default.IssueInstantString), null, new SamlAdvice(), new List <SamlStatement> {
                new SamlAttributeStatement(new SamlSubject(), new List <SamlAttribute> {
                    new SamlAttribute("1", "2", "3")
                })
            });

            IdentityComparer.AreEqual(samlAssertion1, samlAssertion2, context);

            Assert.True(context.Diffs.Count(s => s == "AssertionId:") == 1);
        }
Esempio n. 15
0
        public void RoundTripFromJson()
        {
            var context = new CompareContext {
                Title = "RoundTripFromJson"
            };
            var oidcConfig1 = OpenIdConnectConfiguration.Create(OpenIdConfigData.JsonAllValues);
            var oidcConfig2 = new OpenIdConnectConfiguration(OpenIdConfigData.JsonAllValues);
            var oidcJson1   = OpenIdConnectConfiguration.Write(oidcConfig1);
            var oidcJson2   = OpenIdConnectConfiguration.Write(oidcConfig2);
            var oidcConfig3 = OpenIdConnectConfiguration.Create(oidcJson1);
            var oidcConfig4 = new OpenIdConnectConfiguration(oidcJson2);

            IdentityComparer.AreEqual(oidcConfig1, oidcConfig2, context);
            IdentityComparer.AreEqual(oidcConfig1, oidcConfig3, context);
            IdentityComparer.AreEqual(oidcConfig1, oidcConfig4, context);
            IdentityComparer.AreEqual(oidcJson1, oidcJson2, context);

            TestUtilities.AssertFailIfErrors(context);
        }
Esempio n. 16
0
        public void ReadAction(Saml2TheoryData theoryData)
        {
            var context = TestUtilities.WriteHeader($"{this}.ReadAction", theoryData);

            try
            {
                var reader = XmlUtilities.CreateDictionaryReader(theoryData.Xml);
                var action = (theoryData.Saml2Serializer as Saml2SerializerPublic).ReadActionPublic(reader);
                theoryData.ExpectedException.ProcessNoException(context);

                IdentityComparer.AreEqual(action, theoryData.Action, context);
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }

            TestUtilities.AssertFailIfErrors(context);
        }
Esempio n. 17
0
        public void OidcCreateAuthenticationRequestUrl(string testId, OpenIdConnectMessage message, string expectedMessage)
        {
            TestUtilities.WriteHeader(testId, "OidcCreateAuthenticationRequestUrl", true);
            var context = new CompareContext();

#if NET452
            if (!message.SkuTelemetryValue.Equals("ID_NET451"))
            {
                context.Diffs.Add($"{message.SkuTelemetryValue} != ID_NET451");
            }
#elif NETCOREAPP2_0
            if (!message.SkuTelemetryValue.Equals("ID_NETSTANDARD1_4"))
            {
                context.Diffs.Add($"{message.SkuTelemetryValue} != ID_NETSTANDARD1_4");
            }
#endif
            IdentityComparer.AreEqual(message.CreateAuthenticationRequestUrl(), expectedMessage, context);
            TestUtilities.AssertFailIfErrors(context);
        }
Esempio n. 18
0
        private OpenIdConnectConfiguration RunOpenIdConnectConfigurationTest(object obj, OpenIdConnectConfiguration compareTo, ExpectedException expectedException, bool asString = true)
        {
            bool exceptionHit = false;

            OpenIdConnectConfiguration openIdConnectConfiguration = null;

            try
            {
                if (obj is string)
                {
                    openIdConnectConfiguration = new OpenIdConnectConfiguration(obj as string);
                }
                else if (obj is IDictionary <string, object> )
                {
                    openIdConnectConfiguration = new OpenIdConnectConfiguration(obj as IDictionary <string, object>);
                }
                else
                {
                    if (asString)
                    {
                        openIdConnectConfiguration = new OpenIdConnectConfiguration(obj as string);
                    }
                    else
                    {
                        openIdConnectConfiguration = new OpenIdConnectConfiguration(obj as IDictionary <string, object>);
                    }
                }
                expectedException.ProcessNoException();
            }
            catch (Exception ex)
            {
                exceptionHit = true;
                expectedException.ProcessException(ex);
            }

            if (!exceptionHit && compareTo != null)
            {
                Assert.IsTrue(IdentityComparer.AreEqual(openIdConnectConfiguration, compareTo), "jsonWebKey created from: " + (obj == null ? "NULL" : obj.ToString() + " did not match expected."));
            }

            return(openIdConnectConfiguration);
        }
Esempio n. 19
0
        public void RoundTripJWS()
        {
            TestUtilities.WriteHeader($"{this}.RoundTripToken");
            var context = new CompareContext();

            var tokenHandler = new JsonWebTokenHandler();
            var tokenValidationParameters = new TokenValidationParameters()
            {
                ValidAudience    = Default.Audience,
                ValidIssuer      = Default.Issuer,
                IssuerSigningKey = KeyingMaterial.JsonWebKeyRsa256SigningCredentials.Key,
            };

            string jwtString             = tokenHandler.CreateToken(Default.PayloadString, KeyingMaterial.JsonWebKeyRsa256SigningCredentials);
            var    tokenValidationResult = tokenHandler.ValidateToken(jwtString, tokenValidationParameters);
            var    validatedToken        = tokenValidationResult.SecurityToken as JsonWebToken;

            IdentityComparer.AreEqual(Default.Payload, validatedToken.Payload, context);
            TestUtilities.AssertFailIfErrors(context);
        }
Esempio n. 20
0
        public void CompareSamlAuthorizationDecisionStatements()
        {
            TestUtilities.WriteHeader($"{this}.CompareSamlAuthorizationDecisionStatements", true);
            var context    = new CompareContext($"{this}.CompareSamlAuthorizationDecisionStatements");
            var samlAction = new SamlAction(Guid.NewGuid().ToString());
            var samlAttributeStatement1 =
                new SamlAuthorizationDecisionStatement(new SamlSubject(),
                                                       Guid.NewGuid().ToString(), Default.SamlAccessDecision, new List <SamlAction> {
                samlAction
            });
            var samlAttributeStatement2 =
                new SamlAuthorizationDecisionStatement(new SamlSubject(),
                                                       Guid.NewGuid().ToString(), Default.SamlAccessDecision, new List <SamlAction> {
                samlAction
            });

            IdentityComparer.AreEqual(samlAttributeStatement1, samlAttributeStatement2, context);

            Assert.True(context.Diffs.Count(s => s == "Resource:") == 1);
        }
Esempio n. 21
0
        public void JWECompressionTest(CreateTokenTheoryData theoryData)
        {
            var context = TestUtilities.WriteHeader($"{this}.JWECompressionTest", theoryData);

            try
            {
                var handler = new JsonWebTokenHandler();
                CompressionProviderFactory.Default = theoryData.CompressionProviderFactory;
                var jwtToken         = handler.CreateToken(theoryData.Payload, theoryData.SigningCredentials, theoryData.EncryptingCredentials, theoryData.CompressionAlgorithm);
                var validationResult = handler.ValidateToken(jwtToken, theoryData.ValidationParameters);

                IdentityComparer.AreEqual(theoryData.Payload, (validationResult.SecurityToken as JsonWebToken).Payload, context);

                theoryData.ExpectedException.ProcessNoException(context);
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }
        }
Esempio n. 22
0
        public void ReadAdvice(Saml2TheoryData theoryData)
        {
            TestUtilities.WriteHeader($"{this}.ReadAdvice", theoryData);
            var context = new CompareContext($"{this}.ReadAdvice, {theoryData.TestId}");

            try
            {
                var reader = XmlUtilities.CreateDictionaryReader(theoryData.Xml);
                var advice = (theoryData.Saml2Serializer as Saml2SerializerPublic).ReadAdvicePublic(reader);
                theoryData.ExpectedException.ProcessNoException();

                IdentityComparer.AreEqual(advice, theoryData.Advice, context);
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex);
            }

            TestUtilities.AssertFailIfErrors(context);
        }
Esempio n. 23
0
        public void ReadTransforms(DSigSerializerTheoryData theoryData)
        {
            var context = TestUtilities.WriteHeader($"{this}.ReadTransform", theoryData);

            try
            {
                var reference = new Reference();
                var reader    = XmlUtilities.CreateDictionaryReader(theoryData.Xml);
                theoryData.Serializer.ReadTransforms(reader, reference);
                theoryData.ExpectedException.ProcessNoException(context);
                IdentityComparer.AreEqual(reference.Transforms, theoryData.Transforms, context);
                IdentityComparer.AreEqual(reference.CanonicalizingTransfrom, theoryData.CanonicalizingTransfrom, context);
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }

            TestUtilities.AssertFailIfErrors(context);
        }
Esempio n. 24
0
        public void TryGetClaim()
        {
            var context      = new CompareContext();
            var jsonWebToken = new JsonWebToken("{}", jObject.ToString());

            // Tries to retrieve a value that does not exist in the payload.
            var success = jsonWebToken.TryGetClaim("doesnotexist", out Claim doesNotExist);

            IdentityComparer.AreEqual(null, doesNotExist, context);
            IdentityComparer.AreEqual(false, success, context);

            foreach (var claim in payloadClaims)
            {
                success = jsonWebToken.TryGetClaim(claim.Type, out var claimToCompare);
                IdentityComparer.AreEqual(claim, claimToCompare, context);
                IdentityComparer.AreEqual(true, success, context);
            }

            TestUtilities.AssertFailIfErrors(context);
        }
Esempio n. 25
0
        public void Validate_FromB2CAuthority_WithTfpIssuer_ThrowsException()
        {
            var              context          = new CompareContext();
            Claim            issClaim         = new Claim(ValidatorConstants.ClaimNameIss, ValidatorConstants.B2CIssuerTfp);
            JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(issuer: ValidatorConstants.B2CIssuerTfp, claims: new[] { issClaim });

            AadIssuerValidator validator = CreateIssuerValidator(ValidatorConstants.B2CAuthorityWithV2);

            var exception = Assert.Throws <SecurityTokenInvalidIssuerException>(() =>
                                                                                validator.Validate(
                                                                                    ValidatorConstants.B2CIssuerTfp,
                                                                                    jwtSecurityToken,
                                                                                    new TokenValidationParameters()
            {
                ValidIssuers = new[] { ValidatorConstants.B2CIssuerTfp },
            }));

            IdentityComparer.AreEqual(LogMessages.IDX40002, exception.Message, context);
            TestUtilities.AssertFailIfErrors(context);
        }
Esempio n. 26
0
        public void TestStubTest1(TestStubTheoryData theoryData)
        {
            var context = TestUtilities.WriteHeader($"{this}.TestStubTest1", theoryData);

            try
            {
                var obj = new object();
                theoryData.ExpectedException.ProcessNoException(context);
                if (theoryData.CompareTo != null)
                {
                    IdentityComparer.AreEqual(obj, theoryData.CompareTo, context);
                }
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }

            TestUtilities.AssertFailIfErrors(context);
        }
Esempio n. 27
0
        public void Validate_NullOrEmptyTenantId_ThrowsException()
        {
            var context              = new CompareContext();
            var validator            = new AadIssuerValidator(_httpClient, ValidatorConstants.AadIssuer);
            var jwtSecurityToken     = new JwtSecurityToken();
            var jsonWebToken         = new JsonWebToken($"{{}}", $"{{}}");
            var securityToken        = Substitute.For <SecurityToken>();
            var validationParameters = new TokenValidationParameters();

            var exception = Assert.Throws <SecurityTokenInvalidIssuerException>(() => validator.Validate(ValidatorConstants.AadIssuer, jwtSecurityToken, validationParameters));

            IdentityComparer.AreEqual(LogMessages.IDX40003, exception.Message, context);

            exception = Assert.Throws <SecurityTokenInvalidIssuerException>(() => validator.Validate(ValidatorConstants.AadIssuer, jsonWebToken, validationParameters));
            IdentityComparer.AreEqual(LogMessages.IDX40003, exception.Message, context);

            exception = Assert.Throws <SecurityTokenInvalidIssuerException>(() => validator.Validate(ValidatorConstants.AadIssuer, securityToken, validationParameters));
            IdentityComparer.AreEqual(LogMessages.IDX40003, exception.Message, context);
            TestUtilities.AssertFailIfErrors(context);
        }
        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;
        }
        public void SamlSecurityTokenReadFrom(SamlTheoryData theoryData)
        {
            var context = TestUtilities.WriteHeader($"{this}.SamlSecurityTokenReadFrom", theoryData);

            try
            {
                var sr        = new StringReader(theoryData.SamlTokenTestSet.Xml);
                var reader    = XmlDictionaryReader.CreateDictionaryReader(XmlReader.Create(sr));
                var assertion = theoryData.SamlSerializer.ReadAssertion(reader);
                theoryData.ExpectedException.ProcessNoException(context);

                IdentityComparer.AreEqual(assertion, (theoryData.SamlTokenTestSet.SecurityToken as SamlSecurityToken).Assertion, context);
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }

            TestUtilities.AssertFailIfErrors(context);
        }
Esempio n. 30
0
        public void Validate_NoHttpclientFactory_ReturnsIssuer(string tidClaimType, string tenantId, string issuer)
        {
            var context   = new CompareContext();
            var validator = new AadIssuerValidator(null, issuer);
            var tidClaim  = new Claim(tidClaimType, tenantId);

            var issClaim         = new Claim(ValidatorConstants.ClaimNameIss, issuer);
            var jwtSecurityToken = new JwtSecurityToken(issuer: issuer, claims: new[] { issClaim, tidClaim });

            var tokenValidationParams = new TokenValidationParameters()
            {
                ConfigurationManager = new MockConfigurationManager <OpenIdConnectConfiguration>(new OpenIdConnectConfiguration()
                {
                    Issuer = issuer
                })
            };

            IdentityComparer.AreEqual(issuer, validator.Validate(issuer, jwtSecurityToken, tokenValidationParams), context);
            TestUtilities.AssertFailIfErrors(context);
        }