public void CompareGetClaimAndClaims() { var context = new CompareContext(); var jsonWebTokenHandler = new JsonWebTokenHandler(); var jsonWebTokenString = jsonWebTokenHandler.CreateToken(Default.PayloadString, KeyingMaterial.JsonWebKeyRsa256SigningCredentials); var jsonWebToken = new JsonWebToken(jsonWebTokenString); var claims = jsonWebToken.Claims; foreach (var claim in claims) { var claimFromGetClaim = jsonWebToken.GetClaim(claim.Type); IdentityComparer.AreEqual(claim, claimFromGetClaim, context); } TestUtilities.AssertFailIfErrors(context); }
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 GetIssuerValidator_TwoTenants() { var context = new CompareContext(); var validator = CreateIssuerValidator(ValidatorConstants.AuthorityV1); IdentityComparer.AreEqual(ValidatorConstants.AuthorityV1, validator.AadAuthorityV1, context); IdentityComparer.AreEqual(ValidatorConstants.AuthorityCommonTenantWithV2, validator.AadAuthorityV2, context); IdentityComparer.AreBoolsEqual(false, validator.IsV2Authority, context); validator = CreateIssuerValidator(ValidatorConstants.AuthorityWithTenantSpecified); IdentityComparer.AreEqual(ValidatorConstants.AuthorityWithTenantSpecified, validator.AadAuthorityV1, context); IdentityComparer.AreEqual(ValidatorConstants.AuthorityWithTenantSpecifiedWithV2, validator.AadAuthorityV2, context); IdentityComparer.AreBoolsEqual(false, validator.IsV2Authority, context); TestUtilities.AssertFailIfErrors(context); }
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); 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); 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 CrossToken_ValidateToken() { JwtSecurityTokenHandler jwtHandler = new JwtSecurityTokenHandler(); Saml2TokenHandler saml2Handler = new Saml2TokenHandler(); SamlTokenHandler samlHandler = new SamlTokenHandler(); JwtSecurityTokenHandler.InboundClaimFilter.Add("aud"); JwtSecurityTokenHandler.InboundClaimFilter.Add("exp"); JwtSecurityTokenHandler.InboundClaimFilter.Add("iat"); JwtSecurityTokenHandler.InboundClaimFilter.Add("iss"); JwtSecurityTokenHandler.InboundClaimFilter.Add("nbf"); string jwtToken = IdentityUtilities.CreateJwtToken(IdentityUtilities.DefaultAsymmetricSecurityTokenDescriptor, jwtHandler); // saml tokens created using Microsoft.IdentityModel.Extensions string imSaml2Token = IdentityUtilities.CreateSaml2Token(IdentityUtilities.DefaultAsymmetricSecurityTokenDescriptor, imSaml2Handler); string imSamlToken = IdentityUtilities.CreateSamlToken(IdentityUtilities.DefaultAsymmetricSecurityTokenDescriptor, imSamlHandler); // saml tokens created using System.IdentityModel.Tokens string smSaml2Token = IdentityUtilities.CreateSaml2Token(IdentityUtilities.DefaultAsymmetricSecurityTokenDescriptor, smSaml2Handler); string smSamlToken = IdentityUtilities.CreateSamlToken(IdentityUtilities.DefaultAsymmetricSecurityTokenDescriptor, smSamlHandler); ClaimsPrincipal jwtPrincipal = ValidateToken(jwtToken, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, jwtHandler, ExpectedException.NoExceptionExpected); ClaimsPrincipal imSaml2Principal = ValidateToken(imSaml2Token, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, imSaml2Handler, ExpectedException.NoExceptionExpected); ClaimsPrincipal imSamlPrincipal = ValidateToken(imSamlToken, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, imSamlHandler, ExpectedException.NoExceptionExpected); ClaimsPrincipal smSaml2Principal = ValidateToken(smSaml2Token, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, imSaml2Handler, ExpectedException.NoExceptionExpected); ClaimsPrincipal smSamlPrincipal = ValidateToken(smSamlToken, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, imSamlHandler, ExpectedException.NoExceptionExpected); Assert.IsTrue(IdentityComparer.AreEqual <ClaimsPrincipal>(imSamlPrincipal, imSaml2Principal, new CompareContext { IgnoreSubject = true })); Assert.IsTrue(IdentityComparer.AreEqual <ClaimsPrincipal>(smSamlPrincipal, imSaml2Principal, new CompareContext { IgnoreSubject = true })); Assert.IsTrue(IdentityComparer.AreEqual <ClaimsPrincipal>(smSaml2Principal, imSaml2Principal, new CompareContext { IgnoreSubject = true })); // false = ignore type of objects, we expect all objects in the principal to be of same type (no derived types) // true = ignore subject, claims have a backpointer to their ClaimsIdentity. Most of the time this will be different as we are comparing two different ClaimsIdentities. // true = ignore properties of claims, any mapped claims short to long for JWT's will have a property that represents the short type. Assert.IsTrue(IdentityComparer.AreEqual <ClaimsPrincipal>(jwtPrincipal, imSaml2Principal, new CompareContext { IgnoreType = false, IgnoreSubject = true, IgnoreProperties = true })); JwtSecurityTokenHandler.InboundClaimFilter.Clear(); }
public void CreateJwkClaim(SignedHttpRequestUtilityTheoryData theoryData) { var context = TestUtilities.WriteHeader($"{this}.CreateJwkClaim", theoryData); try { var jwkClaim = SignedHttpRequestUtilities.CreateJwkClaim(theoryData.JsonWebKey); if (!string.IsNullOrEmpty(theoryData.ExpectedJwkClaim)) { IdentityComparer.AreStringsEqual(jwkClaim, theoryData.ExpectedJwkClaim, context); } var jwkJwt = JObject.Parse(jwkClaim); var privateKeyPropertyNames = new List <string>() { JsonWebKeyParameterNames.D, JsonWebKeyParameterNames.DP, JsonWebKeyParameterNames.DQ, JsonWebKeyParameterNames.Oth, JsonWebKeyParameterNames.P, JsonWebKeyParameterNames.Q, JsonWebKeyParameterNames.QI, }; foreach (var privateKeyPropertyName in privateKeyPropertyNames) { if (jwkJwt.ContainsKey(privateKeyPropertyName)) { context.AddDiff($"The resulting jwk claim contains '{privateKeyPropertyName}' field, that represents a private key."); } } if (new JsonWebKey(jwkClaim).HasPrivateKey) { context.AddDiff($"The resulting jwk claim contains a private key."); } theoryData.ExpectedException.ProcessNoException(context); } catch (Exception ex) { theoryData.ExpectedException.ProcessException(ex, context); } TestUtilities.AssertFailIfErrors(context); }
public void QueryStringTest(WsFederationMessageTheoryData theoryData) { var context = TestUtilities.WriteHeader($"{this}.QueryStringTest", theoryData); try { var wsFederationMessage = WsFederationMessage.FromQueryString(theoryData.WsFederationMessageTestSet.Xml); theoryData.ExpectedException.ProcessNoException(); IdentityComparer.AreWsFederationMessagesEqual(wsFederationMessage, theoryData.WsFederationMessageTestSet.WsFederationMessage, context); } catch (Exception ex) { theoryData.ExpectedException.ProcessException(ex); } TestUtilities.AssertFailIfErrors(context); }
public static bool AreStringsEqual(string str1, string str2, CompareContext context) { var localContext = new CompareContext(context); if (!IdentityComparer.ContinueCheckingEquality(str1, str2, localContext)) { return(context.Merge(localContext)); } if (!str1.Equals(str2)) { context.Diffs.Add($"strings are not equal: '{str1}' : '{str2}'"); return(false); } return(true); }
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 static bool AreDateTimesEqual(DateTime?date1, DateTime?date2, CompareContext context) { var localContext = new CompareContext(context); if (!IdentityComparer.ContinueCheckingEquality(date1, date2, localContext)) { return(context.Merge(localContext)); } if (!date1.Equals(date2)) { context.Diffs.Add($"dates are not equal: '{date1}' : '{date2}'"); return(false); } return(true); }
#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); } }
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)); }
public void ReadSignedInfo(DSigSerializerTheoryData theoryData) { var context = TestUtilities.WriteHeader($"{this}.ReadSignedInfo", theoryData); try { var signedInfo = theoryData.Serializer.ReadSignedInfo(XmlUtilities.CreateDictionaryReader(theoryData.Xml)); theoryData.ExpectedException.ProcessNoException(context); IdentityComparer.AreSignedInfosEqual(signedInfo, theoryData.SignedInfo, context); } catch (Exception ex) { theoryData.ExpectedException.ProcessException(ex, context); } 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; }
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); } }
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); }
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); }
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); }
public void CreateClaimsPrincipalCrossVersionTest(CrossTokenVersionTheoryData theoryData) { var context = TestUtilities.WriteHeader($"{this}.CreateClaimsPrincipalCrossVersionTest", theoryData); SecurityToken4x validatedToken4x = null; SecurityToken validatedToken5x = null; ClaimsPrincipal claimsPrincipal4x = null; ClaimsPrincipal claimsPrincipal5x = null; try { claimsPrincipal4x = CrossVersionUtility.ValidateSaml2Token(theoryData.TokenString4x, theoryData.ValidationParameters4x, out validatedToken4x); } catch (Exception ex) { context.Diffs.Add($"CrossVersionTokenValidationTestsData.ValidateToken threw: '{ex}'."); } try { claimsPrincipal5x = new Tokens.Saml2.Saml2SecurityTokenHandler().ValidateToken(theoryData.TokenString4x, theoryData.ValidationParameters5x, out validatedToken5x); } catch (Exception ex) { context.Diffs.Add($"Tokens.Saml.SamlSecurityTokenHandler().ValidateToken threw: '{ex}'."); } AreSaml2TokensEqual(validatedToken4x, validatedToken5x, context); IdentityComparer.AreClaimsPrincipalsEqual(claimsPrincipal4x, claimsPrincipal5x, context); // verify the results from asynchronous and synchronous are the same TokenValidationResult tokenValidationResult = null; try { tokenValidationResult = new Tokens.Saml2.Saml2SecurityTokenHandler().ValidateTokenAsync(theoryData.TokenString4x, theoryData.ValidationParameters5x).Result; } catch (Exception ex) { context.Diffs.Add($"CrossVersionTokenValidationTestsData.ValidateToken threw: '{ex}'."); } IdentityComparer.AreClaimsIdentitiesEqual(claimsPrincipal5x.Identity as ClaimsIdentity, tokenValidationResult.ClaimsIdentity, context); TestUtilities.AssertFailIfErrors(context); }
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); }
/// <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); }
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)); }
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); }
public void DateTimeISO8061Claim() { var context = new CompareContext(); TestUtilities.WriteHeader($"{this}.DateTimeISO8061Claim"); var encodedTokenWithDateTimeISO8061Claim = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGFpbV9hc19kYXRldGltZSI6IjIwMTktMTEtMTVUMTQ6MzE6MjEuNjEwMTMyNloifQ.yYcHSl-rNT2nHe8Nb0aWe6Qu3E0ZOn2_OUidpxuw0wk"; var claimA = new JwtSecurityTokenHandler().ReadJwtToken(encodedTokenWithDateTimeISO8061Claim).Claims.First(); var claimB = new JsonWebTokenHandler().ReadJsonWebToken(encodedTokenWithDateTimeISO8061Claim).Claims.First(); // both claims should be equal IdentityComparer.AreClaimsEqual(claimA, claimB, context); TestUtilities.AssertFailIfErrors(context); // both claim value types should be DateTime Assert.True(string.Equals(claimA.ValueType, ClaimValueTypes.DateTime), "ClaimValueType is not DateTime."); // claim value shouldn't contain any quotes Assert.DoesNotContain("\"", claimA.Value); }
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); }
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); }
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); }
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); }
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); }
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); }
private void ReducePsms(IList<InputFile> csvFiles, UniquePeptideType uniquePeptideType, bool isBatched = false) { string msg = "Converting PSMs into unique peptides based "; IEqualityComparer<Peptide> comparer; switch (uniquePeptideType) { default: msg += "on sequence only"; comparer = new SequenceComparer(); break; case UniquePeptideType.Mass: msg += "on mass"; comparer = new MassComparer(); break; case UniquePeptideType.SequenceAndModifications: msg += "on sequence and positional modifications"; comparer = new SequenceModComparer(); break; case UniquePeptideType.SequenceAndModLocations: msg += "on sequence and modification locations"; comparer = new SequenceAndModPositionComparer(); break; case UniquePeptideType.SequenceAndMass: msg += "on sequence and mass"; comparer = new SequenceMassComparer(); break; case UniquePeptideType.Nothing: msg += "on nothing (no reduction)"; comparer = new IdentityComparer<Peptide>(); break; } Log(msg); foreach (InputFile csvFile in csvFiles) { csvFile.ReducePsms(comparer); Log(string.Format("{0:N0} unique peptides remain from {1:N0} PSMs from {2}", csvFile.Peptides.Count, csvFile.PeptideSpectralMatches.Count, csvFile.Name)); } if (!isBatched) return; Dictionary<Peptide, Peptide> peptideDictionary = new Dictionary<Peptide, Peptide>(comparer); foreach (Peptide peptide in csvFiles.SelectMany(csvFile => csvFile.Peptides)) { Peptide realPeptide; if (peptideDictionary.TryGetValue(peptide, out realPeptide)) { foreach (PSM psm in peptide.PSMs) { realPeptide.AddPsm(psm); } } else { Peptide newPeptide = new Peptide(peptide); peptideDictionary.Add(newPeptide, newPeptide); } } _allPeptides = peptideDictionary.Values.ToList(); Log(string.Format("{0:N0} unique peptides from all files [Batched]", _allPeptides.Count)); }
/// <summary> /// Create a new instance of the IdentityMap that has no /// iteration order. /// </summary> /// <returns>A new IdentityMap based on a Hashtable.</returns> public static IDictionary Instantiate( int size ) { IHashCodeProvider ihcp = new NHibernate.IdentityHashCodeProvider(); IComparer comp = new IdentityComparer(); return new IdentityMap( new Hashtable( size, ihcp, comp ) ); }
/// <summary> /// Create a new instance of the IdentityMap that has an /// iteration order of the order the objects were added /// to the Map. /// </summary> /// <returns>A new IdentityMap based on ListDictionary.</returns> public static IDictionary InstantiateSequenced( int size ) { IHashCodeProvider ihcp = new IdentityHashCodeProvider(); IComparer comp = new IdentityComparer(); return new IdentityMap( new SequencedHashMap( size, ihcp, comp ) ); }