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); } }
private void RunAlgorithmMappingTest(string jwt, TokenValidationParameters validationParameters, JwtSecurityTokenHandler handler, ExpectedException expectedException) { try { Token validatedToken; handler.ValidateToken(jwt, validationParameters, out validatedToken); expectedException.ProcessNoException(); } catch (Exception ex) { expectedException.ProcessException(ex); } }
#pragma warning restore CS3016 // Arrays as attribute arguments is not CLS-compliant public void InvalidEncodedSegments(string testId, string jwt, ExpectedException ee) { try { var jwtToken = new JwtSecurityToken(jwt); ee.ProcessNoException(); TestUtilities.CallAllPublicInstanceAndStaticPropertyGets(jwtToken, testId); } catch (Exception ex) { ee.ProcessException(ex); } }
#pragma warning restore CS3016 // Arrays as attribute arguments is not CLS-compliant public void InvalidRegExSegments(string testId, string jwt, ExpectedException ee) { try { new JwtSecurityToken(jwt); ee.ProcessNoException(); } catch (Exception ex) { ee.ProcessException(ex); } }
public void Constructors() { OpenIdConnectMessage openIdConnectMessage = new OpenIdConnectMessage(); Assert.Equal(openIdConnectMessage.IssuerAddress, string.Empty); openIdConnectMessage = new OpenIdConnectMessage() { IssuerAddress = "http://www.got.jwt.com" }; Assert.Equal(openIdConnectMessage.IssuerAddress, "http://www.got.jwt.com"); ExpectedException expectedException = ExpectedException.NoExceptionExpected; string json = @"{""response_mode"":""responseMode"", ""response_type"":""responseType"", ""refresh_token"":""refreshToken""}"; string badJson = @"{""response_mode"":""responseMode"";""respone_mode"":""badResponeMode""}"; // null stirng json expectedException = ExpectedException.ArgumentNullException(); TestJsonStringConstructor((string)null, expectedException); // bad string json expectedException = ExpectedException.ArgumentException("IDX10106"); TestJsonStringConstructor(badJson, expectedException); // no exception, well-formed json expectedException = ExpectedException.NoExceptionExpected; openIdConnectMessage = TestJsonStringConstructor(json, expectedException); Assert.True(openIdConnectMessage.RefreshToken.Equals("refreshToken"), "openIdConnectMessage.RefreshToken does not match expected value: refreshToken"); Assert.True(openIdConnectMessage.ResponseMode.Equals("responseMode"), "openIdConnectMessage.ResponseMode does not match expected value: refreshToken"); Assert.True(openIdConnectMessage.ResponseType.Equals("responseType"), "openIdConnectMessage.ResponseType does not match expected value: refreshToken"); Assert.True(openIdConnectMessage.ClientId == null, "openIdConnectMessage.ClientId is not null"); // no exception, using JObject ctor expectedException = ExpectedException.NoExceptionExpected; try { openIdConnectMessage = new OpenIdConnectMessage(JObject.Parse(json)); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } Assert.True(openIdConnectMessage.RefreshToken.Equals("refreshToken"), "openIdConnectMessage.RefreshToken does not match expected value: refreshToken"); Assert.True(openIdConnectMessage.ResponseMode.Equals("responseMode"), "openIdConnectMessage.ResponseMode does not match expected value: refreshToken"); Assert.True(openIdConnectMessage.ResponseType.Equals("responseType"), "openIdConnectMessage.ResponseType does not match expected value: refreshToken"); Assert.True(openIdConnectMessage.ClientId == null, "openIdConnectMessage.ClientId is not null"); // test with an empty JObject openIdConnectMessage = new OpenIdConnectMessage(new JObject()); }
public void MatchX5t() { X509SecurityKey signingKey = KeyingMaterial.X509SecurityKeySelfSigned2048_SHA256; X509SecurityKey validateKey = KeyingMaterial.X509SecurityKeySelfSigned2048_SHA256_Public; // Assume SigningKey.KeyId doesn't match validationParameters.IssuerSigningKey.KeyId signingKey.KeyId = null; var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha256Signature); var header = new JwtHeader(signingCredentials); header.Add(JwtHeaderParameterNames.X5t, Base64UrlEncoder.Encode(KeyingMaterial.CertSelfSigned2048_SHA256.GetCertHash())); var payload = new JwtPayload(); payload.AddClaims(ClaimSets.DefaultClaims); var jwtToken = new JwtSecurityToken(header, payload); var handler = new JwtSecurityTokenHandler(); var jwt = handler.WriteToken(jwtToken); var validationParameters = new TokenValidationParameters { RequireExpirationTime = false, RequireSignedTokens = true, ValidateAudience = false, ValidateIssuer = false, ValidateLifetime = false, }; validationParameters.IssuerSigningKey = validateKey; SecurityToken validatedSecurityToken = null; var cp = handler.ValidateToken(jwt, validationParameters, out validatedSecurityToken); validateKey = KeyingMaterial.X509SecurityKeySelfSigned2048_SHA384_Public; validationParameters.IssuerSigningKey = validateKey; ExpectedException expectedException = ExpectedException.SecurityTokenInvalidSignatureException("IDX10503:"); try { cp = handler.ValidateToken(jwt, validationParameters, out validatedSecurityToken); } catch (Exception ex) { expectedException.ProcessException(ex); } }
private void ValidateDerived(string jwt, DerivedJwtSecurityTokenHandler handler, TokenValidationParameters validationParameters, ExpectedException expectedException, List <string> errors) { try { Token validatedToken; handler.ValidateToken(jwt, validationParameters, out validatedToken); if ((handler.Jwt as DerivedJwtSecurityToken) == null) { errors.Add("(handler.Jwt as DerivedJwtSecurityToken) == null"); } if (!handler.ReadTokenCalled) { errors.Add("!handler.ReadTokenCalled"); } if (!handler.ValidateAudienceCalled) { errors.Add("!handler.ValidateAudienceCalled"); } if (!handler.ValidateIssuerCalled) { errors.Add("!handler.ValidateIssuerCalled"); } if (!handler.ValidateIssuerSigningKeyCalled) { errors.Add("!handler.ValidateIssuerSigningKeyCalled"); } if (!handler.ValidateLifetimeCalled) { errors.Add("!handler.ValidateLifetimeCalled"); } if (!handler.ValidateSignatureCalled) { errors.Add("!handler.ValidateSignatureCalled"); } expectedException.ProcessNoException(errors); } catch (Exception ex) { expectedException.ProcessException(ex, errors); } }
private string ValidateIssuer(string issuer, TokenValidationParameters validationParameters, DerivedSamlSecurityTokenHandler samlSecurityTokenHandler, ExpectedException expectedException) { string returnVal = string.Empty; try { returnVal = samlSecurityTokenHandler.ValidateIssuerPublic(issuer, new DerivedSaml2SecurityToken(), validationParameters); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } return(returnVal); }
private void GetDocument(string address, IDocumentRetriever docRetriever, ExpectedException ee) { try { string doc = docRetriever.GetDocumentAsync(address, CancellationToken.None).Result; ee.ProcessNoException(); } catch (AggregateException ex) { ex.Handle((x) => { ee.ProcessException(x); return(true); }); } }
private OpenIdConnectMessage TestJsonStringConstructor(string json, ExpectedException expectedException) { OpenIdConnectMessage openIdConnectMessage = null; try { openIdConnectMessage = new OpenIdConnectMessage(json); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } return(openIdConnectMessage); }
private bool CanReadToken(string securityToken, Saml2SecurityTokenHandler samlSecurityTokenHandler, ExpectedException expectedException) { bool canReadToken = false; try { canReadToken = samlSecurityTokenHandler.CanReadToken(securityToken); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } return(canReadToken); }
private ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, ISecurityTokenValidator tokenValidator, ExpectedException expectedException) { ClaimsPrincipal princiapl = null; try { SecurityToken validatedToken; princiapl = tokenValidator.ValidateToken(securityToken, validationParameters, out validatedToken); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } return(princiapl); }
#pragma warning restore CS3016 // Arrays as attribute arguments is not CLS-compliant public void CreateJWETokens(string testId, string jweToken, TokenValidationParameters validationParameters, JwtPayload expectedPayload, ExpectedException ee) { var handler = new JwtSecurityTokenHandler(); handler.InboundClaimTypeMap.Clear(); try { SecurityToken token = null; var claimsPrincipal = handler.ValidateToken(jweToken, validationParameters, out token); ee.ProcessNoException(); var outerToken = token as JwtSecurityToken; Assert.True(outerToken != null, "ValidateToken should not return a null token for the JWE token."); TestUtilities.CallAllPublicInstanceAndStaticPropertyGets(outerToken, testId); Assert.True(outerToken.InnerToken != null, "ValidateToken should not return a null token for the inner JWE token."); TestUtilities.CallAllPublicInstanceAndStaticPropertyGets(outerToken.InnerToken, testId); var context = new CompareContext(); if (!IdentityComparer.AreEqual(outerToken.Payload, outerToken.InnerToken.Payload, context)) { context.Diffs.Add("outerToken.Payload != outerToken.InnerToken.Payload"); } foreach (KeyValuePair <string, object> claim in expectedPayload) { if (!outerToken.Payload.ContainsKey(claim.Key)) { context.Diffs.Add(String.Format("expectedPayload claim {0} : {1} doesn't exist in outerToken.Payload", claim.Key, claim.Value)); } else { if ((outerToken.Payload[claim.Key] != null && !outerToken.Payload[claim.Key].Equals(claim.Value)) || (outerToken.Payload[claim.Key] == null && claim.Value != null)) { context.Diffs.Add(String.Format("expectedPayload claim {0} doesn't match in outerToken.Payload. Expected value: {1}. Outer token value: {2}", claim.Key, claim.Value, outerToken.Payload[claim.Key])); } } } TestUtilities.AssertFailIfErrors(string.Format(CultureInfo.InvariantCulture, "CreateJWETokens: "), context.Diffs); } catch (Exception ex) { ee.ProcessException(ex); } }
private async Task<OpenIdConnectConfiguration> GetConfigurationAsync(string uri, ExpectedException expectedException, OpenIdConnectConfiguration expectedConfiguration, CompareContext context) { OpenIdConnectConfiguration openIdConnectConfiguration = null; try { openIdConnectConfiguration = await OpenIdConnectConfigurationRetriever.GetAsync(uri, new FileDocumentRetriever(), CancellationToken.None); expectedException.ProcessNoException(context); } catch (Exception exception) { expectedException.ProcessException(exception, context.Diffs); } if (expectedConfiguration != null) IdentityComparer.AreEqual(openIdConnectConfiguration, expectedConfiguration, context); return openIdConnectConfiguration; }
private async Task<OpenIdConnectConfiguration> GetConfigurationFromHttpAsync(string uri, ExpectedException expectedException, OpenIdConnectConfiguration expectedConfiguration = null) { OpenIdConnectConfiguration openIdConnectConfiguration = null; try { openIdConnectConfiguration = await OpenIdConnectConfigurationRetriever.GetAsync(uri, CancellationToken.None); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } if (expectedConfiguration != null) { Assert.True(IdentityComparer.AreEqual(openIdConnectConfiguration, expectedConfiguration)); } return openIdConnectConfiguration; }
private async Task<OpenIdConnectConfiguration> GetConfigurationFromMixedAsync(string primaryDocument, ExpectedException expectedException, OpenIdConnectConfiguration expectedConfiguration = null) { OpenIdConnectConfiguration openIdConnectConfiguration = null; try { openIdConnectConfiguration = await OpenIdConnectConfigurationRetriever.GetAsync("primary", new TestDocumentRetriever(primaryDocument, new FileDocumentRetriever()), CancellationToken.None); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } if (expectedConfiguration != null) { Assert.True(IdentityComparer.AreEqual(openIdConnectConfiguration, expectedConfiguration)); } return openIdConnectConfiguration; }
public void Constructors() { WsFederationMessage wsFederationMessage = new WsFederationMessage(); Assert.AreEqual(wsFederationMessage.IssuerAddress, string.Empty); wsFederationMessage = new WsFederationMessage("http://www.got.jwt.com"); Assert.AreEqual(wsFederationMessage.IssuerAddress, "http://www.got.jwt.com"); ExpectedException expectedException = ExpectedException.ArgumentNullException("issuerAddress"); try { wsFederationMessage = new WsFederationMessage((string)null); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } }
#pragma warning restore CS3016 // Arrays as attribute arguments is not CLS-compliant public void RoundTripJWETokens(string testId, SecurityTokenDescriptor tokenDescriptor, TokenValidationParameters validationParameters, ExpectedException ee) { var handler = new JwtSecurityTokenHandler(); handler.InboundClaimTypeMap.Clear(); var jweCreatedInMemory = handler.CreateJwtSecurityToken(tokenDescriptor); try { SecurityToken token = null; var claimsPrincipal = handler.ValidateToken(jweCreatedInMemory.RawData, validationParameters, out token); ee.ProcessNoException(); var outerToken = token as JwtSecurityToken; Assert.True(outerToken != null, "ValidateToken should not return a null token for the JWE token."); TestUtilities.CallAllPublicInstanceAndStaticPropertyGets(outerToken, testId); Assert.True(outerToken.InnerToken != null, "ValidateToken should not return a null token for the inner JWE token."); TestUtilities.CallAllPublicInstanceAndStaticPropertyGets(outerToken.InnerToken, testId); var context = new CompareContext(); if (!IdentityComparer.AreEqual(jweCreatedInMemory.Payload, outerToken.Payload, context)) { context.Diffs.Add("jweCreatedInMemory.Payload != jweValidated.Payload"); } if (!IdentityComparer.AreEqual(jweCreatedInMemory.Payload, outerToken.InnerToken.Payload, context)) { context.Diffs.Add("jweCreatedInMemory.Payload != jweValidated.InnerToken.Payload"); } TestUtilities.AssertFailIfErrors(string.Format(CultureInfo.InvariantCulture, "RoundTripJWETokens: "), context.Diffs); } catch (Exception ex) { ee.ProcessException(ex); } }
public void Publics() { string value1 = "value1"; string value2 = "value2"; string param1 = "param1"; string param2 = "param2"; AuthenticationProtocolMessage authenticationProtocolMessage = new DerivedAuthenticationProtocolMessage() { IssuerAddress = "http://www.gotjwt.com" }; ExpectedException expectedException = ExpectedException.ArgumentNullException(substringExpected: "parameter"); try { authenticationProtocolMessage.GetParameter(null); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } expectedException = ExpectedException.ArgumentNullException(substringExpected: "parameter"); try { authenticationProtocolMessage.RemoveParameter(null); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } expectedException = ExpectedException.ArgumentNullException(substringExpected: "parameter"); try { authenticationProtocolMessage.SetParameter(null, null); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } authenticationProtocolMessage.SetParameter(param1, value1); authenticationProtocolMessage.RemoveParameter(param2); Assert.Equal(authenticationProtocolMessage.GetParameter(param1), value1); authenticationProtocolMessage.RemoveParameter(param1); Assert.Null(authenticationProtocolMessage.GetParameter(param1)); authenticationProtocolMessage.SetParameter(param1, value1); authenticationProtocolMessage.SetParameter(param1, value2); authenticationProtocolMessage.SetParameter(param2, value2); authenticationProtocolMessage.SetParameter(param2, value1); Assert.Equal(authenticationProtocolMessage.GetParameter(param1), value2); Assert.Equal(authenticationProtocolMessage.GetParameter(param2), value1); authenticationProtocolMessage = new DerivedAuthenticationProtocolMessage() { IssuerAddress = "http://www.gotjwt.com" }; authenticationProtocolMessage.SetParameter("bob", " "); string queryString = authenticationProtocolMessage.BuildRedirectUrl(); Assert.NotNull(queryString); Assert.Contains("bob", queryString); authenticationProtocolMessage.IssuerAddress = string.Empty; queryString = authenticationProtocolMessage.BuildRedirectUrl(); Assert.NotNull(queryString); }
public void EmbeddedTokenConstructor1(string testId, JwtSecurityTokenTestVariation outerTokenVariation, JwtSecurityTokenTestVariation innerTokenVariation, string jwt, ExpectedException ee) { JwtSecurityToken outerJwt = null; JwtSecurityToken innerJwt = null; // create inner token try { if (innerTokenVariation != null) { innerJwt = CreateToken(innerTokenVariation); } } catch (Exception ex) { ee.ProcessException(ex); } // create outer token try { if (string.IsNullOrEmpty(jwt)) { outerJwt = new JwtSecurityToken( header: outerTokenVariation.Header, innerToken: innerJwt, rawHeader: outerTokenVariation.RawHeader, rawEncryptedKey: outerTokenVariation.RawEncryptedKey, rawInitializationVector: outerTokenVariation.RawInitializationVector, rawCiphertext: outerTokenVariation.RawCiphertext, rawAuthenticationTag: outerTokenVariation.RawAuthenticationTag); } else { outerJwt = new JwtSecurityToken(jwt); } ee.ProcessNoException(); } catch (Exception ex) { ee.ProcessException(ex); } try { // ensure we can get to every outer token property if (outerJwt != null && (ee == null || ee.TypeExpected == null)) { TestUtilities.CallAllPublicInstanceAndStaticPropertyGets(outerJwt, testId); } if (null != outerTokenVariation.ExpectedJwtSecurityToken) { Assert.True(IdentityComparer.AreEqual(outerTokenVariation.ExpectedJwtSecurityToken, outerJwt)); } } catch (Exception ex) { Assert.True(false, string.Format("Testcase: {0}. UnExpected when getting a properties: '{1}'", outerTokenVariation.Name, ex.ToString())); } try { // ensure we can get to every inner token property if (innerJwt != null && (ee == null || ee.TypeExpected == null)) { TestUtilities.CallAllPublicInstanceAndStaticPropertyGets(innerJwt, testId); } if (null != innerTokenVariation && null != innerTokenVariation.ExpectedJwtSecurityToken) { Assert.True(IdentityComparer.AreEqual(innerTokenVariation.ExpectedJwtSecurityToken, innerJwt)); } } catch (Exception ex) { Assert.True(false, string.Format("Testcase: {0}. UnExpected when getting a properties: '{1}'", testId, ex.ToString())); } try { if (outerJwt != null && innerJwt != null && (ee == null || ee.TypeExpected == null)) { // confirm properties of outer token match our expectation Assert.Equal(outerJwt.InnerToken, innerJwt); CheckPayloadProperties(outerJwt, innerJwt); CheckOuterTokenProperties(outerJwt, outerTokenVariation); } } catch (Exception ex) { Assert.True(false, string.Format("Testcase: {0}. Unexpected inequality between outer and inner token properties: '{1}'", testId, ex.ToString())); } }
public void GetConfiguration() { var docRetriever = new FileDocumentRetriever(); var configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever); var context = new CompareContext($"{this}.GetConfiguration"); // AutomaticRefreshInterval interval should return same config. var configuration = configManager.GetConfigurationAsync().Result; TestUtilities.SetField(configManager, "_metadataAddress", "OpenIdConnectMetadata2.json"); var configuration2 = configManager.GetConfigurationAsync().Result; IdentityComparer.AreEqual(configuration, configuration2, context); if (!object.ReferenceEquals(configuration, configuration2)) { context.Diffs.Add("!object.ReferenceEquals(configuration, configuration2)"); } // AutomaticRefreshInterval should pick up new bits. configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever); TestUtilities.SetField(configManager, "_automaticRefreshInterval", TimeSpan.FromMilliseconds(1)); configuration = configManager.GetConfigurationAsync().Result; TestUtilities.SetField(configManager, "_lastRefresh", DateTimeOffset.UtcNow - TimeSpan.FromHours(1)); TestUtilities.SetField(configManager, "_metadataAddress", "OpenIdConnectMetadata2.json"); configManager.RequestRefresh(); configuration2 = configManager.GetConfigurationAsync().Result; if (IdentityComparer.AreEqual(configuration, configuration2)) { context.Diffs.Add("IdentityComparer.AreEqual(configuration, configuration2)"); } if (object.ReferenceEquals(configuration, configuration2)) { context.Diffs.Add("object.ReferenceEquals(configuration, configuration2) (2)"); } // RefreshInterval is set to MaxValue configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever); configuration = configManager.GetConfigurationAsync().Result; configManager.RefreshInterval = TimeSpan.MaxValue; TestUtilities.SetField(configManager, "_metadataAddress", "OpenIdConnectMetadata2.json"); configuration2 = configManager.GetConfigurationAsync().Result; IdentityComparer.AreEqual(configuration, configuration2, context); if (!object.ReferenceEquals(configuration, configuration2)) { context.Diffs.Add("!object.ReferenceEquals(configuration, configuration2) (3)"); } // Refresh should have no effect configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever); configuration = configManager.GetConfigurationAsync().Result; configManager.RefreshInterval = TimeSpan.FromHours(10); configManager.RequestRefresh(); configuration2 = configManager.GetConfigurationAsync().Result; IdentityComparer.AreEqual(configuration, configuration2, context); if (!object.ReferenceEquals(configuration, configuration2)) { context.Diffs.Add("!object.ReferenceEquals(configuration, configuration2) (4)"); } // Refresh should force pickup of new config configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever); configuration = configManager.GetConfigurationAsync().Result; TestUtilities.SetField(configManager, "_lastRefresh", DateTimeOffset.UtcNow - TimeSpan.FromHours(1)); configManager.RequestRefresh(); TestUtilities.SetField(configManager, "_metadataAddress", "OpenIdConnectMetadata2.json"); configuration2 = configManager.GetConfigurationAsync().Result; if (IdentityComparer.AreEqual(configuration, configuration2)) { context.Diffs.Add("IdentityComparer.AreEqual(configuration, configuration2), should be different"); } if (object.ReferenceEquals(configuration, configuration2)) { context.Diffs.Add("object.ReferenceEquals(configuration, configuration2)"); } // Refresh set to MaxValue configManager.RefreshInterval = TimeSpan.MaxValue; configuration = configManager.GetConfigurationAsync().Result; IdentityComparer.AreEqual(configuration, configuration2, context); if (!object.ReferenceEquals(configuration, configuration2)) { context.Diffs.Add("!object.ReferenceEquals(configuration, configuration2)"); } // get configuration from http address, should throw configManager = new ConfigurationManager <OpenIdConnectConfiguration>("http://someaddress.com", new OpenIdConnectConfigurationRetriever()); var ee = new ExpectedException(typeof(InvalidOperationException), "IDX20803:", typeof(ArgumentException)); try { configuration = configManager.GetConfigurationAsync().Result; ee.ProcessNoException(context); } catch (AggregateException ex) { // this should throw, because last configuration retrived was null Assert.Throws <AggregateException>(() => configuration = configManager.GetConfigurationAsync().Result); ex.Handle((x) => { ee.ProcessException(x, context); return(true); }); } // get configuration from https address, should throw configManager = new ConfigurationManager <OpenIdConnectConfiguration>("https://someaddress.com", new OpenIdConnectConfigurationRetriever()); ee = new ExpectedException(typeof(InvalidOperationException), "IDX20803:", typeof(IOException)); try { configuration = configManager.GetConfigurationAsync().Result; ee.ProcessNoException(context); } catch (AggregateException ex) { // this should throw, because last configuration retrived was null Assert.Throws <AggregateException>(() => configuration = configManager.GetConfigurationAsync().Result); ex.Handle((x) => { ee.ProcessException(x, context); return(true); }); } // get configuration with unsuccessful HTTP response status code configManager = new ConfigurationManager <OpenIdConnectConfiguration>("https://httpstat.us/429", new OpenIdConnectConfigurationRetriever()); ee = new ExpectedException(typeof(InvalidOperationException), "IDX20803:", typeof(IOException)); try { configuration = configManager.GetConfigurationAsync().Result; ee.ProcessNoException(context); } catch (AggregateException ex) { // this should throw, because last configuration retrived was null Assert.Throws <AggregateException>(() => configuration = configManager.GetConfigurationAsync().Result); ex.Handle((x) => { ee.ProcessException(x, context); return(true); }); } // Unable to obtain a new configuration, but _currentConfiguration is not null so it should be returned. configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever); configuration = configManager.GetConfigurationAsync().Result; TestUtilities.SetField(configManager, "_lastRefresh", DateTimeOffset.UtcNow - TimeSpan.FromHours(1)); configManager.RequestRefresh(); TestUtilities.SetField(configManager, "_metadataAddress", "http://someaddress.com"); configuration2 = configManager.GetConfigurationAsync().Result; IdentityComparer.AreEqual(configuration, configuration2, context); if (!object.ReferenceEquals(configuration, configuration2)) { context.Diffs.Add("!object.ReferenceEquals(configuration, configuration2)"); } TestUtilities.AssertFailIfErrors(context); }
public void GetConfiguration() { FileDocumentRetriever docRetriever = new FileDocumentRetriever(); ConfigurationManager <OpenIdConnectConfiguration> configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever); // AutomaticRefreshInterval interval should return same config. OpenIdConnectConfiguration configuration = configManager.GetConfigurationAsync().Result; TestUtilities.SetField(configManager, "_metadataAddress", "OpenIdConnectMetadata2.json"); OpenIdConnectConfiguration configuration2 = configManager.GetConfigurationAsync().Result; Assert.True(IdentityComparer.AreEqual(configuration, configuration2)); Assert.True(object.ReferenceEquals(configuration, configuration2)); // AutomaticRefreshInterval should pick up new bits. configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever); TestUtilities.SetField(configManager, "_automaticRefreshInterval", TimeSpan.FromMilliseconds(1)); configuration = configManager.GetConfigurationAsync().Result; TestUtilities.SetField(configManager, "_lastRefresh", DateTimeOffset.UtcNow - TimeSpan.FromHours(1)); TestUtilities.SetField(configManager, "_metadataAddress", "OpenIdConnectMetadata2.json"); configManager.RequestRefresh(); configuration2 = configManager.GetConfigurationAsync().Result; Assert.False(IdentityComparer.AreEqual(configuration, configuration2)); Assert.False(object.ReferenceEquals(configuration, configuration2)); // RefreshInterval is set to MaxValue configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever); configuration = configManager.GetConfigurationAsync().Result; configManager.RefreshInterval = TimeSpan.MaxValue; TestUtilities.SetField(configManager, "_metadataAddress", "OpenIdConnectMetadata2.json"); configuration2 = configManager.GetConfigurationAsync().Result; Assert.True(IdentityComparer.AreEqual(configuration, configuration2)); Assert.True(object.ReferenceEquals(configuration, configuration2)); // Refresh should have no effect configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever); configuration = configManager.GetConfigurationAsync().Result; configManager.RefreshInterval = TimeSpan.FromHours(10); configManager.RequestRefresh(); configuration2 = configManager.GetConfigurationAsync().Result; Assert.True(IdentityComparer.AreEqual(configuration, configuration2)); Assert.True(object.ReferenceEquals(configuration, configuration2)); // Refresh should force pickup of new config configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever); configuration = configManager.GetConfigurationAsync().Result; TestUtilities.SetField(configManager, "_lastRefresh", DateTimeOffset.UtcNow - TimeSpan.FromHours(1)); configManager.RequestRefresh(); TestUtilities.SetField(configManager, "_metadataAddress", "OpenIdConnectMetadata2.json"); configuration2 = configManager.GetConfigurationAsync().Result; Assert.False(object.ReferenceEquals(configuration, configuration2)); Assert.False(IdentityComparer.AreEqual(configuration, configuration2)); // Refresh set to MaxValue configManager.RefreshInterval = TimeSpan.MaxValue; configuration = configManager.GetConfigurationAsync().Result; Assert.True(object.ReferenceEquals(configuration, configuration2)); Assert.True(IdentityComparer.AreEqual(configuration, configuration2)); // get configuration from http address, should throw configManager = new ConfigurationManager <OpenIdConnectConfiguration>("http://someaddress.com", new OpenIdConnectConfigurationRetriever()); ExpectedException ee = new ExpectedException(typeof(InvalidOperationException), "IDX10803:", typeof(ArgumentException)); try { configuration = configManager.GetConfigurationAsync().Result; ee.ProcessNoException(); } catch (AggregateException ex) { // this should throw, because last configuration retrived was null Assert.Throws <AggregateException>(() => configuration = configManager.GetConfigurationAsync().Result); ex.Handle((x) => { ee.ProcessException(x); return(true); }); } }
public void RoundTripSamlPSignatureAfterAssertion() { var context = new CompareContext($"{this}.RoundTripSamlPSignatureAfterAssertion"); ExpectedException expectedException = ExpectedException.NoExceptionExpected; var samlpTokenKey = KeyingMaterial.RsaSigningCreds_4096_Public.Key; var samlpTokenSigningCredentials = KeyingMaterial.RsaSigningCreds_4096; var samlpKey = KeyingMaterial.RsaSigningCreds_2048_Public.Key; var samlpSigningCredentials = KeyingMaterial.RsaSigningCreds_2048; try { // write samlp var settings = new XmlWriterSettings { Encoding = new UTF8Encoding(false) }; var buffer = new MemoryStream(); var esw = new EnvelopedSignatureWriter(XmlWriter.Create(buffer, settings), samlpSigningCredentials, "id-uAOhNLe7abGB6WGPk"); esw.WriteStartElement("ns0", "Response", "urn:oasis:names:tc:SAML:2.0:protocol"); esw.WriteAttributeString("ns1", "urn:oasis:names:tc:SAML:2.0:assertion"); esw.WriteAttributeString("ns2", "http://www.w3.org/2000/09/xmldsig#"); esw.WriteAttributeString("Destination", "https://tnia.eidentita.cz/fpsts/processRequest.aspx"); esw.WriteAttributeString("ID", "id-uAOhNLe7abGB6WGPk"); esw.WriteAttributeString("InResponseTo", "ida5714d006fcc430c92aacf34ab30b166"); esw.WriteAttributeString("IssueInstant", "2019-04-08T10:30:49Z"); esw.WriteAttributeString("Version", "2.0"); esw.WriteStartElement("ns1", "Issuer"); esw.WriteAttributeString("Format", "urn:oasis:names:tc:SAML:2.0:nameid-format:entity"); esw.WriteString("https://mojeid.regtest.nic.cz/saml/idp.xml"); esw.WriteEndElement(); esw.WriteStartElement("ns0", "Status", null); esw.WriteStartElement("ns0", "StatusCode", null); esw.WriteAttributeString("Value", "urn:oasis:names:tc:SAML:2.0:status:Success"); esw.WriteEndElement(); esw.WriteEndElement(); Saml2Serializer samlSerializer = new Saml2Serializer(); Saml2Assertion assertion = CreateAssertion(samlpTokenSigningCredentials); samlSerializer.WriteAssertion(esw, assertion); esw.WriteSignature(); esw.WriteEndElement(); var xml = Encoding.UTF8.GetString(buffer.ToArray()); // read samlp and verify signatures XmlReader reader = XmlUtilities.CreateDictionaryReader(xml); IXmlElementReader tokenReaders = new TokenReaders(new List <SecurityTokenHandler> { new Saml2SecurityTokenHandler() }); EnvelopedSignatureReader envelopedReader = new EnvelopedSignatureReader(reader, tokenReaders); while (envelopedReader.Read()) { ; } foreach (var item in tokenReaders.Items) { if (item is Saml2SecurityToken samlToken) { samlToken.Assertion.Signature.Verify(samlpTokenKey); } } envelopedReader.Signature.Verify(samlpKey, samlpKey.CryptoProviderFactory); expectedException.ProcessNoException(context); } catch (Exception ex) { expectedException.ProcessException(ex, context); } TestUtilities.AssertFailIfErrors(context); }
public void RoundTripJWETokens(string testId, SecurityTokenDescriptor tokenDescriptor, TokenValidationParameters validationParameters, ExpectedException ee) { var handler = new JwtSecurityTokenHandler(); handler.InboundClaimTypeMap.Clear(); var jweCreatedInMemory = handler.CreateJwtSecurityToken(tokenDescriptor); var jweCreatedInMemory2 = handler.CreateJwtSecurityToken ( tokenDescriptor.Issuer, tokenDescriptor.Audience, tokenDescriptor.Subject, tokenDescriptor.NotBefore, tokenDescriptor.Expires, tokenDescriptor.IssuedAt, tokenDescriptor.SigningCredentials, tokenDescriptor.EncryptingCredentials ); try { SecurityToken token = null; var claimsPrincipal = handler.ValidateToken(jweCreatedInMemory.RawData, validationParameters, out token); ee.ProcessNoException(); var outerToken = token as JwtSecurityToken; Assert.True(outerToken != null, "ValidateToken should not return a null token for the JWE token."); TestUtilities.CallAllPublicInstanceAndStaticPropertyGets(outerToken, testId); Assert.True(outerToken.InnerToken != null, "ValidateToken should not return a null token for the inner JWE token."); TestUtilities.CallAllPublicInstanceAndStaticPropertyGets(outerToken.InnerToken, testId); var context = new CompareContext(); context.PropertiesToIgnoreWhenComparing = new Dictionary <Type, List <string> > { { typeof(JwtHeader), new List <string> { "Item" } }, { typeof(JwtPayload), new List <string> { "Item" } } }; if (!IdentityComparer.AreEqual(jweCreatedInMemory.Payload, outerToken.Payload, context)) { context.Diffs.Add("jweCreatedInMemory.Payload != jweValidated.Payload"); } if (!IdentityComparer.AreEqual(jweCreatedInMemory.Payload, jweCreatedInMemory2.Payload, context)) { context.Diffs.Add("jweCreatedInMemory.Payload != jweCreatedInMemory2.Payload"); } if (!IdentityComparer.AreEqual(jweCreatedInMemory.Payload, outerToken.InnerToken.Payload, context)) { context.Diffs.Add("jweCreatedInMemory.Payload != jweValidated.InnerToken.Payload"); } TestUtilities.AssertFailIfErrors(string.Format(CultureInfo.InvariantCulture, "RoundTripJWETokens: "), context.Diffs); } catch (Exception ex) { ee.ProcessException(ex); } }