public void X509SecurityKey_Constructor() { X509SecurityKey x509SecurityKey; ExpectedException expectedException = new ExpectedException(typeExpected: typeof(ArgumentNullException), substringExpected: "certificate"); try { x509SecurityKey = new X509SecurityKey(null); expectedException.ProcessNoException(); } catch(Exception exception) { expectedException.ProcessException(exception); } X509Certificate2 x509Certificate2 = KeyingMaterial.DefaultCert_2048; expectedException = ExpectedException.NoExceptionExpected; try { x509SecurityKey = new X509SecurityKey(x509Certificate2); Assert.ReferenceEquals(x509Certificate2, x509SecurityKey.Certificate); } catch (Exception exception) { expectedException.ProcessException(exception); } }
private void RunAudienceTest(IEnumerable<string> audiences, SecurityToken securityToken, TokenValidationParameters validationParameters, ExpectedException ee) { try { Validators.ValidateAudience(audiences, securityToken, validationParameters); ee.ProcessNoException(); } catch(Exception ex) { ee.ProcessException(ex); } }
public void TestExpectedExceptionSerialize() { ExpectedException obj = new ExpectedException(); ExceptionBase eb = new ExceptionBase(obj); DataContractSerializer formater = new DataContractSerializer(typeof(ExceptionBase)); using (Stream stream = new MemoryStream()) { formater.WriteObject(stream, eb); stream.Seek(0, SeekOrigin.Begin); ExceptionBase exception = (ExceptionBase)formater.ReadObject(stream); } }
public ExpectedJwtSecurityTokenRequirement ( uint? tokenSize = null, Int32? clock = null, uint? life = null, X509CertificateValidator cert = null, string name = JwtConstants.ReservedClaims.Sub, string role = null, X509RevocationMode? revMode = null, X509CertificateValidationMode? certMode = null, StoreLocation? storeLoc = null, ExpectedException expectedException = null, string handler = JwtSecurityTokenHandlerType, string requirement = Elements.JwtSecurityTokenRequirement, string attributeEx1 = "", string attributeEx2 = "", string attributeEx3 = "", string attributeEx4 = "", string elementEx1 = comment, string elementEx2 = comment, string elementEx3 = comment, string elementEx4 = comment, string elementEx5 = comment, string elementEx6 = comment, string elementClose = closeRequirement ) { MaxTokenSizeInBytes = tokenSize; NameClaimType = name; RoleClaimType = role; CertValidator = cert; ClockSkewInSeconds = clock; DefaultTokenLifetimeInMinutes = life; CertRevocationMode = revMode; CertValidationMode = certMode; CertStoreLocation = storeLoc; ExpectedException = expectedException ?? ExpectedException.NoExceptionExpected; string[] sParams = { handler, requirement, CertRevocationMode == null ? string.Empty : Attribute( Attributes.RevocationMode, CertRevocationMode.Value.ToString() ), attributeEx1, CertValidationMode == null ? string.Empty : Attribute( Attributes.ValidationMode, CertValidationMode.Value.ToString() ), attributeEx2, CertValidator == null ? string.Empty : Attribute( Attributes.Validator, CertValidator.GetType().ToString() +", System.IdentityModel.Tokens.Jwt.Tests" ), attributeEx3, CertStoreLocation == null ? string.Empty : Attribute( Attributes.TrustedStoreLocation, CertStoreLocation.ToString() ), attributeEx4, elementEx1, ClockSkewInSeconds == null ? string.Empty : ElementValue( Elements.MaxClockSkewInMinutes, ClockSkewInSeconds.Value.ToString() ), elementEx2, MaxTokenSizeInBytes == null ? string.Empty : ElementValue( Elements.MaxTokenSizeInBytes, MaxTokenSizeInBytes.Value.ToString() ), elementEx3, DefaultTokenLifetimeInMinutes == null ? string.Empty : ElementValue( Elements.DefaultTokenLifetimeInMinutes, DefaultTokenLifetimeInMinutes.Value.ToString() ), elementEx4, NameClaimType == null ? string.Empty : ElementValue( Elements.NameClaimType, NameClaimType ), elementEx5, RoleClaimType == null ? string.Empty : ElementValue( Elements.RoleClaimType, RoleClaimType ), elementEx6, elementClose, }; Config = string.Format(ElementTemplate, sParams); }
public void NamedKeySecurityKeyIdentifierClause_Constructor() { NamedKeySecurityKeyIdentifierClause namedKeySecurityKeyIdentifierClause; ExpectedException expectedException = new ExpectedException(typeExpected: typeof(ArgumentNullException), substringExpected: "name"); try { namedKeySecurityKeyIdentifierClause = new NamedKeySecurityKeyIdentifierClause(null, null); expectedException.ProcessNoException(); } catch(Exception exception) { expectedException.ProcessException(exception); } expectedException = new ExpectedException(typeExpected: typeof(ArgumentNullException), substringExpected: "id"); try { namedKeySecurityKeyIdentifierClause = new NamedKeySecurityKeyIdentifierClause("name", null); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } expectedException = ExpectedException.ArgumentNullException(substringExpected: "name"); try { namedKeySecurityKeyIdentifierClause = new NamedKeySecurityKeyIdentifierClause(name: " ", id: "id"); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } expectedException = ExpectedException.ArgumentNullException(substringExpected: "id"); try { namedKeySecurityKeyIdentifierClause = new NamedKeySecurityKeyIdentifierClause("name", " "); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } }
private void ValidateDerived(string jwt, DerivedJwtSecurityTokenHandler handler, TokenValidationParameters validationParameters, ExpectedException expectedException) { try { SecurityToken validatedToken; handler.ValidateToken(jwt, validationParameters, out validatedToken); Assert.IsNotNull(handler.Jwt as DerivedJwtSecurityToken); Assert.IsTrue(handler.ReadTokenCalled); Assert.IsFalse(handler.ValidateAudienceCalled); Assert.IsTrue(handler.ValidateIssuerCalled); Assert.IsTrue(handler.ValidateIssuerSigningKeyCalled); Assert.IsTrue(handler.ValidateLifetimeCalled); Assert.IsTrue(handler.ValidateSignatureCalled); expectedException.ProcessNoException(); } catch (Exception ex) { expectedException.ProcessException(ex); } }
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; }
public void ContentTypeHeaderParsingWithClientBehaviorTest() { // In V1 and V2 clients, application/xml and application/atom+xml are valid for all of the following payload kinds. Func <ODataPayloadKind, bool> isXmlPayloadKind = pk => pk == ODataPayloadKind.Feed || pk == ODataPayloadKind.Entry || pk == ODataPayloadKind.MetadataDocument || pk == ODataPayloadKind.Property || pk == ODataPayloadKind.EntityReferenceLink || pk == ODataPayloadKind.Collection || pk == ODataPayloadKind.ServiceDocument || pk == ODataPayloadKind.Error; // In V3 (whether under client knob or not), we should be spec // compliant and only allow application/atom+xml for feeds and // entries and application/xml for all other xml payload kinds. // When running the test cases, we replace ShouldSucceedForPayloadKind // with isXmlPayloadKind when dealing with pre-V3 clients. var testCases = new[] { new ContentTypeTestCase { ContentType = "application/atom+xml", ExpectedFormat = ODataFormat.Atom, }, new ContentTypeTestCase { ContentType = "application/xml", ExpectedFormat = ODataFormat.Atom, }, }; IEdmModel model = Microsoft.Test.OData.Utils.Metadata.TestModels.BuildTestModel(); IEnumerable <ODataPayloadKind> payloadKinds = TestReaderUtils.ODataPayloadKinds.Where(k => k != ODataPayloadKind.Batch && k != ODataPayloadKind.Unsupported); this.CombinatorialEngineProvider.RunCombinations( testCases, payloadKinds, this.ReaderTestConfigurationProvider.AtomFormatConfigurations, (testCase, payloadKind, testConfiguration) => { // Run under the client knob. testConfiguration = testConfiguration.CloneAndApplyBehavior(TestODataBehaviorKind.WcfDataServicesClient); testConfiguration.MessageReaderSettings.EnableAtom = false; if (IgnoreTestCase(payloadKind, testConfiguration)) { return; } // If version is V1 or V2, we should succeed for all xml payload kinds if the mime type is application/atom+xml or application/xml. Func <ODataPayloadKind, bool> shouldSucceedForPayloadKind = testCase.ShouldSucceedForPayloadKind; // Get supported media types to use in expected error message. string supportedMediaTypes; if (payloadKind == ODataPayloadKind.Value || payloadKind == ODataPayloadKind.BinaryValue) { supportedMediaTypes = TestMediaTypeUtils.GetSupportedMediaTypes(ODataPayloadKind.Value) + ", " + TestMediaTypeUtils.GetSupportedMediaTypes(ODataPayloadKind.BinaryValue); } else { supportedMediaTypes = TestMediaTypeUtils.GetSupportedMediaTypes(payloadKind); } ExpectedException expectedException = testCase.ExpectedException == null ? shouldSucceedForPayloadKind != null && shouldSucceedForPayloadKind(payloadKind) ? null : ODataExpectedExceptions.ODataContentTypeException("MediaTypeUtils_CannotDetermineFormatFromContentType", supportedMediaTypes, testCase.ContentType) : testCase.ExpectedException; ODataPayloadElement payloadElement = CreatePayloadElement(model, payloadKind, testConfiguration); ODataFormat expectedFormat = testCase.ExpectedFormat; ReaderContentTypeTestDescriptor testDescriptor = new ReaderContentTypeTestDescriptor(this.Settings) { PayloadElement = payloadElement, PayloadEdmModel = model, ExpectedFormat = expectedFormat, ContentType = testCase.ContentType, ExpectedException = expectedException }; testDescriptor.RunTest(testConfiguration); }); }
private PayloadWriterTestDescriptor<ODataItem> CreateDefaultStreamMetadataTestDescriptor( IEdmModel model, string typeName, ODataStreamReferenceValue mediaResourceValue, ExpectedException expectedException = null) { return new PayloadWriterTestDescriptor<ODataItem>( this.Settings, new ODataEntry() { TypeName = typeName, MediaResource = mediaResourceValue, SerializationInfo = new ODataFeedAndEntrySerializationInfo() { NavigationSourceEntityTypeName = typeName, NavigationSourceName = "MySet", ExpectedTypeName = typeName }}, (tc) => { if (expectedException != null) { return new WriterTestExpectedResults(this.Settings.ExpectedResultSettings) { ExpectedException2 = expectedException }; } else { if (tc.Format == ODataFormat.Atom) { return new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings) { FragmentExtractor = (result) => new XElement("root"), Xml = "<root/>" }; } else { return new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings) { FragmentExtractor = (result) => new JsonObject(), Json = "{}" }; } } }) { Model = model }; }
public static ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, ISecurityTokenValidator tokenValidator, ExpectedException expectedException) { ClaimsPrincipal retVal = null; try { SecurityToken validatedToken; retVal = tokenValidator.ValidateToken(securityToken, validationParameters, out validatedToken); expectedException.ProcessNoException(); } catch (Exception ex) { expectedException.ProcessException(ex); } return retVal; }
public BatchWriterTestDescriptor(Settings settings, InvocationAndOperationDescriptor[] invocationsAndOperationDescriptors, ExpectedException expectedException, Uri baseUri = null) { ExceptionUtilities.CheckArgumentNotNull(expectedException, "expectedException"); this.TestDescriptorSettings = settings; this.invocationsAndOperationDescriptors = invocationsAndOperationDescriptors; this.expectedResultCallback = CreateExpectedErrorResultCallback(null, null, expectedException, this.TestDescriptorSettings.ExpectedResultSettings); this.baseUri = baseUri; }
public void JwtSecurityTokenHandler_IssuerValidation() { JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); string jwt = (tokenHandler.CreateToken(issuer: IdentityUtilities.DefaultIssuer, audience: IdentityUtilities.DefaultAudience, signingCredentials: IdentityUtilities.DefaultAsymmetricSigningCredentials) as JwtSecurityToken).RawData; TokenValidationParameters validationParameters = new TokenValidationParameters() { IssuerSigningToken = IdentityUtilities.DefaultAsymmetricSigningToken, ValidateAudience = false, ValidateLifetime = false }; // ValidateIssuer == true // validIssuer null, validIssuers null ExpectedException ee = new ExpectedException(typeof(SecurityTokenInvalidIssuerException), substringExpected: "IDX10204"); TestUtilities.ValidateToken(jwt, validationParameters, tokenHandler, ee); // no issuers ee = new ExpectedException(typeof(SecurityTokenInvalidIssuerException), substringExpected: "IDX10205"); validationParameters.ValidIssuers = new List<string>(); TestUtilities.ValidateToken(jwt, validationParameters, tokenHandler, ee); // delegate ignored on virtual call ee = ExpectedException.NoExceptionExpected; validationParameters.IssuerValidator = IdentityUtilities.IssuerValidatorEcho; TestUtilities.ValidateToken(jwt, validationParameters, tokenHandler, ee); // VaidateIssuer == false ee = ExpectedException.NoExceptionExpected; validationParameters.ValidateIssuer = false; TestUtilities.ValidateToken(jwt, validationParameters, tokenHandler, ee); // no issuers should NOT fail. vaidate issuer is not needed. ee = ExpectedException.NoExceptionExpected; validationParameters.ValidIssuers = new List<string>() { "http://Simple.CertData_2049" }; TestUtilities.ValidateToken(jwt, validationParameters, tokenHandler, ee); // matches ValidIssuer validationParameters.ValidateIssuer = true; validationParameters.ValidIssuer = IdentityUtilities.DefaultIssuer; TestUtilities.ValidateToken(jwt, validationParameters, tokenHandler, ExpectedException.NoExceptionExpected); // matches ValidIssuers validationParameters.ValidIssuer = null; validationParameters.ValidIssuers = new string[] { "http://Simple.CertData_2048", IdentityUtilities.DefaultIssuer }; TestUtilities.ValidateToken(jwt, validationParameters, tokenHandler, ExpectedException.NoExceptionExpected); validationParameters.ValidateIssuer = false; validationParameters.IssuerValidator = IdentityUtilities.IssuerValidatorThrows; TestUtilities.ValidateToken(jwt, validationParameters, tokenHandler, ExpectedException.NoExceptionExpected); }
private string ValidateIssuer(string issuer, TokenValidationParameters validationParameters, SamlSecurityToken samlToken, PublicSamlSecurityTokenHandler samlSecurityTokenHandler, ExpectedException expectedException) { string returnVal = string.Empty; try { returnVal = samlSecurityTokenHandler.ValidateIssuerPublic(issuer, samlToken, validationParameters); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } return returnVal; }
public static DSigSerializerTheoryData TransformsTest(TransformsTestSet testSet, ExpectedException expectedException = null, bool first = false) { return(new DSigSerializerTheoryData { ExpectedException = expectedException ?? ExpectedException.NoExceptionExpected, First = first, Reference = testSet.Reference, TestId = testSet.TestId ?? nameof(testSet), Transforms = testSet.Transforms, Xml = testSet.Xml, }); }
private bool RunCanReadStringVariation(string securityToken, JwtSecurityTokenHandler tokenHandler, ExpectedException expectedException) { bool retVal = false; try { retVal = tokenHandler.CanReadToken(securityToken); expectedException.ProcessNoException(); } catch (Exception ex) { expectedException.ProcessException(ex); } return retVal; }
public void GetSets() { var context = new GetSetContext { PropertyNamesAndSetGetValue = new List <KeyValuePair <string, List <object> > > { new KeyValuePair <string, List <object> >("TransformFactory", new List <object> { TransformFactory.Default }), new KeyValuePair <string, List <object> >("MaximumReferenceTransforms", new List <object> { 5, 11, 1 }) }, Object = new DSigSerializer() }; TestUtilities.GetSet(context); TestUtilities.SetGet(new DSigSerializer(), "MaximumReferenceTransforms", 0, ExpectedException.NoExceptionExpected, context); TestUtilities.SetGet(new DSigSerializer(), "MaximumReferenceTransforms", -1, ExpectedException.ArgumentOutOfRangeException("IDX30600:"), context); TestUtilities.AssertFailIfErrors("DSigSerializerTests_GetSets", context.Errors); }
public static DSigSerializerTheoryData TransformsTest(TransformTestSet testSet, ExpectedException expectedException = null, bool first = false) { return(new DSigSerializerTheoryData { CanonicalizingTransfrom = testSet.CanonicalizingTransfrom, ExpectedException = expectedException ?? ExpectedException.NoExceptionExpected, First = first, TestId = testSet.TestId, Transform = testSet.Transform, Transforms = new List <Transform> { testSet.Transform }, Xml = testSet.Xml, }); }
public static DSigSerializerTheoryData SignedInfoTest(SignedInfoTestSet testSet, ExpectedException expectedException = null, bool first = false) { return(new DSigSerializerTheoryData { ExpectedException = expectedException ?? ExpectedException.NoExceptionExpected, First = first, SignedInfo = testSet.SignedInfo, TestId = testSet.TestId ?? nameof(testSet), Xml = testSet.Xml, }); }
public static void AddValidateAudienceTheoryData(List <TokenTheoryData> theoryData) { theoryData.Add(new TokenTheoryData { Audiences = new List <string>(), First = true, ExpectedException = ExpectedException.ArgumentNullException("IDX10000:"), TestId = "TokenValidationParameters null", ValidationParameters = null, }); theoryData.Add(new TokenTheoryData { Audiences = new List <string>(), TestId = "ValidateAudience = false", ValidationParameters = new TokenValidationParameters { ValidateAudience = false, }, }); theoryData.Add(new TokenTheoryData { Audiences = new List <string>(), ExpectedException = ExpectedException.SecurityTokenInvalidAudienceException("IDX10208:"), TestId = "no audiences in validationParameters", ValidationParameters = new TokenValidationParameters { ValidateAudience = true, }, }); theoryData.Add(new TokenTheoryData { Audiences = new List <string> { "John" }, ExpectedException = ExpectedException.SecurityTokenInvalidAudienceException("IDX10208:"), TestId = "audience has value, tvp has no values", ValidationParameters = new TokenValidationParameters { ValidateAudience = true, }, }); theoryData.Add(new TokenTheoryData { Audiences = new List <string> { "John" }, ExpectedException = ExpectedException.SecurityTokenInvalidAudienceException("IDX10214:"), TestId = "audience not matched", ValidationParameters = new TokenValidationParameters { ValidateAudience = true, ValidAudience = "frank" }, }); theoryData.Add(new TokenTheoryData { Audiences = new List <string> { "John" }, TestId = "AudienceValidator returns true", ValidationParameters = new TokenValidationParameters { AudienceValidator = (aud, token, type) => { return(true); }, ValidateAudience = true, ValidAudience = "frank" }, }); theoryData.Add(new TokenTheoryData { Audiences = new List <string> { "John" }, ExpectedException = ExpectedException.SecurityTokenInvalidAudienceException(), TestId = "AudienceValidator throws, validateAudience false", ValidationParameters = new TokenValidationParameters { AudienceValidator = ValidationDelegates.AudienceValidatorThrows, ValidateAudience = false, ValidAudience = "frank" }, }); }
public static void AddValidateIssuerTheoryData(List <TokenTheoryData> theoryData) { theoryData.Add(new TokenTheoryData { ExpectedException = ExpectedException.ArgumentNullException("IDX10000:"), First = true, Issuer = "bob", TestId = "ValidationParameters null", ValidationParameters = null, }); theoryData.Add(new TokenTheoryData { TestId = "ValidateIssuer == false", ValidationParameters = new TokenValidationParameters { ValidateIssuer = false }, }); theoryData.Add(new TokenTheoryData { ExpectedException = ExpectedException.SecurityTokenInvalidIssuerException("IDX10205:"), Issuer = "bob", TestId = "Issuer not matched", ValidationParameters = new TokenValidationParameters { ValidIssuer = "frank" } }); theoryData.Add(new TokenTheoryData { Issuer = "bob", TestId = "Issuer matched", ValidationParameters = new TokenValidationParameters { ValidateAudience = false, ValidIssuer = "bob" } }); theoryData.Add(new TokenTheoryData { ExpectedException = ExpectedException.SecurityTokenInvalidIssuerException(substringExpected: "IDX10205:"), Issuer = "bob", TestId = "ValidIssuers set but not matched", ValidationParameters = new TokenValidationParameters { ValidateAudience = false, ValidIssuers = new List <string> { "john", "paul", "george", "ringo" } } }); theoryData.Add(new TokenTheoryData { Issuer = "bob", TestId = "IssuerValidator - echo", ValidationParameters = new TokenValidationParameters { IssuerValidator = ValidationDelegates.IssuerValidatorEcho, ValidateAudience = false } }); }
private static PayloadWriterTestDescriptor.WriterTestExpectedResultCallback CreateErrorResultCallback( ExpectedException expectedException, ODataFormat onlyForFormat, WriterTestExpectedResults.Settings expectedResultSettings) { return testConfiguration => { if (onlyForFormat != null && testConfiguration.Format != onlyForFormat) { return null; } return new WriterTestExpectedResults(expectedResultSettings) { // Replace the expected exception for requests where an ODataException is expected ExpectedException2 = testConfiguration.IsRequest && (expectedException != null && expectedException.ExpectedExceptionType.Equals(typeof(ODataException))) ? ODataExpectedExceptions.ODataException("ODataMessageWriter_ServiceDocumentInRequest") : expectedException, }; }; }
public void GetSets() { TestUtilities.WriteHeader($"{this}.GetSets", "GetSets", true); var configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), new FileDocumentRetriever()); Type type = typeof(ConfigurationManager <OpenIdConnectConfiguration>); PropertyInfo[] properties = type.GetProperties(); if (properties.Length != 2) { Assert.True(false, "Number of properties has changed from 2 to: " + properties.Length + ", adjust tests"); } var defaultAutomaticRefreshInterval = ConfigurationManager <OpenIdConnectConfiguration> .DefaultAutomaticRefreshInterval; var defaultRefreshInterval = ConfigurationManager <OpenIdConnectConfiguration> .DefaultRefreshInterval; var context = new GetSetContext { PropertyNamesAndSetGetValue = new List <KeyValuePair <string, List <object> > > { new KeyValuePair <string, List <object> >("AutomaticRefreshInterval", new List <object> { defaultAutomaticRefreshInterval, TimeSpan.FromHours(1), TimeSpan.FromHours(10) }), new KeyValuePair <string, List <object> >("RefreshInterval", new List <object> { defaultRefreshInterval, TimeSpan.FromHours(1), TimeSpan.FromHours(10) }), }, Object = configManager, }; TestUtilities.GetSet(context); TestUtilities.SetGet(configManager, "AutomaticRefreshInterval", TimeSpan.FromMilliseconds(1), ExpectedException.ArgumentOutOfRangeException(substringExpected: "IDX20107:"), context); TestUtilities.SetGet(configManager, "RefreshInterval", TimeSpan.FromMilliseconds(1), ExpectedException.ArgumentOutOfRangeException(substringExpected: "IDX20106:"), context); TestUtilities.SetGet(configManager, "RefreshInterval", Timeout.InfiniteTimeSpan, ExpectedException.ArgumentOutOfRangeException(substringExpected: "IDX20106:"), context); TestUtilities.AssertFailIfErrors("ConfigurationManager_GetSets", context.Errors); }
private void RunWriteXmlWriterVariation(XmlWriter writer, SecurityToken token, SecurityTokenHandler tokenHandler, ExpectedException ee) { try { tokenHandler.WriteToken(writer, token); ee.ProcessNoException(); } catch(Exception ex) { ee.ProcessException(ex); } }
public void GetConfiguration() { var docRetriever = new FileDocumentRetriever(); var configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever); var context = new CompareContext($"{this}.GetConfiguration"); // AutomaticRefreshInterval interval should return same config. var configuration = configManager.GetConfigurationAsync().Result; TestUtilities.SetField(configManager, "_metadataAddress", "OpenIdConnectMetadata2.json"); var configuration2 = configManager.GetConfigurationAsync().Result; IdentityComparer.AreEqual(configuration, configuration2, context); if (!object.ReferenceEquals(configuration, configuration2)) { context.Diffs.Add("!object.ReferenceEquals(configuration, configuration2)"); } // AutomaticRefreshInterval should pick up new bits. configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever); TestUtilities.SetField(configManager, "_automaticRefreshInterval", TimeSpan.FromMilliseconds(1)); configuration = configManager.GetConfigurationAsync().Result; TestUtilities.SetField(configManager, "_lastRefresh", DateTimeOffset.UtcNow - TimeSpan.FromHours(1)); TestUtilities.SetField(configManager, "_metadataAddress", "OpenIdConnectMetadata2.json"); configManager.RequestRefresh(); configuration2 = configManager.GetConfigurationAsync().Result; if (IdentityComparer.AreEqual(configuration, configuration2)) { context.Diffs.Add("IdentityComparer.AreEqual(configuration, configuration2)"); } if (object.ReferenceEquals(configuration, configuration2)) { context.Diffs.Add("object.ReferenceEquals(configuration, configuration2) (2)"); } // RefreshInterval is set to MaxValue configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever); configuration = configManager.GetConfigurationAsync().Result; configManager.RefreshInterval = TimeSpan.MaxValue; TestUtilities.SetField(configManager, "_metadataAddress", "OpenIdConnectMetadata2.json"); configuration2 = configManager.GetConfigurationAsync().Result; IdentityComparer.AreEqual(configuration, configuration2, context); if (!object.ReferenceEquals(configuration, configuration2)) { context.Diffs.Add("!object.ReferenceEquals(configuration, configuration2) (3)"); } // Refresh should have no effect configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever); configuration = configManager.GetConfigurationAsync().Result; configManager.RefreshInterval = TimeSpan.FromHours(10); configManager.RequestRefresh(); configuration2 = configManager.GetConfigurationAsync().Result; IdentityComparer.AreEqual(configuration, configuration2, context); if (!object.ReferenceEquals(configuration, configuration2)) { context.Diffs.Add("!object.ReferenceEquals(configuration, configuration2) (4)"); } // Refresh should force pickup of new config configManager = new ConfigurationManager <OpenIdConnectConfiguration>("OpenIdConnectMetadata.json", new OpenIdConnectConfigurationRetriever(), docRetriever); configuration = configManager.GetConfigurationAsync().Result; TestUtilities.SetField(configManager, "_lastRefresh", DateTimeOffset.UtcNow - TimeSpan.FromHours(1)); configManager.RequestRefresh(); TestUtilities.SetField(configManager, "_metadataAddress", "OpenIdConnectMetadata2.json"); configuration2 = configManager.GetConfigurationAsync().Result; if (IdentityComparer.AreEqual(configuration, configuration2)) { context.Diffs.Add("IdentityComparer.AreEqual(configuration, configuration2), should be different"); } if (object.ReferenceEquals(configuration, configuration2)) { context.Diffs.Add("object.ReferenceEquals(configuration, configuration2)"); } // Refresh set to MaxValue configManager.RefreshInterval = TimeSpan.MaxValue; configuration = configManager.GetConfigurationAsync().Result; IdentityComparer.AreEqual(configuration, configuration2, context); if (!object.ReferenceEquals(configuration, configuration2)) { context.Diffs.Add("!object.ReferenceEquals(configuration, configuration2)"); } // get configuration from http address, should throw configManager = new ConfigurationManager <OpenIdConnectConfiguration>("http://someaddress.com", new OpenIdConnectConfigurationRetriever()); var ee = new ExpectedException(typeof(InvalidOperationException), "IDX20803:", typeof(ArgumentException)); try { configuration = configManager.GetConfigurationAsync().Result; ee.ProcessNoException(context); } catch (AggregateException ex) { // this should throw, because last configuration retrived was null Assert.Throws <AggregateException>(() => configuration = configManager.GetConfigurationAsync().Result); ex.Handle((x) => { ee.ProcessException(x, context); return(true); }); } TestUtilities.AssertFailIfErrors(context); }
private JwtSecurityToken RunReadStringVariation(string securityToken, JwtSecurityTokenHandler tokenHandler, ExpectedException expectedException) { JwtSecurityToken retVal = null; try { retVal = tokenHandler.ReadToken(securityToken) as JwtSecurityToken; expectedException.ProcessNoException(); } catch (Exception ex) { expectedException.ProcessException(ex); } return retVal; }
/// <summary> /// Converts a <see cref="PayloadReaderTestDescriptor"/> to an in-stream error <see cref="PayloadReaderTestDescriptor"/>. /// </summary> /// <param name="descriptor">The <see cref="PayloadReaderTestDescriptor"/> to convert.</param> /// <param name="format">The <see cref="ODataFormat"/> the test descriptor is created for.</param> /// <returns>An in-stream error <see cref="PayloadReaderTestDescriptor"/> based on the <paramref name="descriptor"/>.</returns> /// <remarks>The <paramref name="descriptor"/> is expected to represent a top-level error payload test descriptor.</remarks> internal static PayloadReaderTestDescriptor ToInStreamErrorTestDescriptor(this PayloadReaderTestDescriptor descriptor, ODataFormat format) { ExceptionUtilities.CheckArgumentNotNull(descriptor, "descriptor"); ExceptionUtilities.CheckArgumentNotNull(format, "format"); ExceptionUtilities.Assert(descriptor.PayloadElement.ElementType == ODataPayloadElementType.ODataErrorPayload, "Only error payloads expected."); ExceptionUtilities.Assert(descriptor.ExpectedResultCallback == null, "No expected results callback expected."); ExceptionUtilities.Assert(descriptor.PayloadEdmModel == null, "No model expected."); // Model that defines the CityType to be used for wrapping the error payload to convert it into an in-stream error. IEdmModel testModel = Test.OData.Utils.Metadata.TestModels.BuildTestModel(); bool isValidTopLevelError = descriptor.ExpectedException == null; ODataPayloadElement wrappedPayloadElement = null; ExpectedException expectedException = null; if (format == ODataFormat.Json) { IEdmEntitySet citiesSet = testModel.EntityContainer.FindEntitySet("Cities"); IEdmEntityType cityType = testModel.FindType("TestModel.CityType") as IEdmEntityType; var jsonRepresentation = (JsonPayloadElementRepresentationAnnotation)descriptor.PayloadElement.GetAnnotation(typeof(JsonPayloadElementRepresentationAnnotation)); ExceptionUtilities.Assert(jsonRepresentation != null, "Expected a format-specific annotation."); JsonObject jsonObject = (JsonObject)jsonRepresentation.Json; // wrap the existing payload in an entity of type 'CityType'; the existing payload is used as value of the 'PoliceStation' property JsonObject wrapperObject = (JsonObject)JsonTextPreservingParser.ParseValue(new StringReader("{ \"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#TestModel.DefaultContainer.Cities/$entity\" }")); wrapperObject.Add(new JsonProperty("PoliceStation", jsonObject)); // replace the payload and Json representation of the test descriptor and set the expected error message wrappedPayloadElement = PayloadBuilder.Entity("TestModel.CityType") .ExpectedEntityType(cityType, citiesSet) .JsonRepresentation(wrapperObject); if (isValidTopLevelError) { // if we have a valid top-level error we expect an ODataErrorException to be thrown. ODataError error = ConvertErrorPayload((ODataErrorPayload)descriptor.PayloadElement, /*forAtom*/ false); expectedException = ODataExpectedExceptions.ODataErrorException(error, "ODataErrorException_GeneralError"); } else { // if the top-level error is too deeply recursive, we expect to fail in the same way for the in-stream error. if (descriptor.ExpectedException.ExpectedMessage.ResourceIdentifier == "ValidationUtils_RecursionDepthLimitReached") { expectedException = descriptor.ExpectedException; } else { // otherwise, if the top-level error is not valid, we expect an error message that the first // property of the invalid top-level error object is not defined on type OfficeType. string firstPropertyName = jsonObject.Properties.First().Name; expectedException = ODataExpectedExceptions.ODataException("ValidationUtils_PropertyDoesNotExistOnType", firstPropertyName, "TestModel.OfficeType"); } } } else { throw new TaupoInvalidOperationException("Unsupported format for error test descriptor found: " + format.GetType().Name); } return(new PayloadReaderTestDescriptor(descriptor) { PayloadElement = wrappedPayloadElement, PayloadEdmModel = testModel, ExpectedResultPayloadElement = tc => descriptor.PayloadElement, ExpectedException = expectedException, }); }
private void ValidateAudience() { Saml2SecurityTokenHandler tokenHandler = new Saml2SecurityTokenHandler(); ExpectedException expectedException; string samlString = IdentityUtilities.CreateSaml2Token(); TokenValidationParameters tokenValidationParameters = new TokenValidationParameters { IssuerSigningToken = IdentityUtilities.DefaultAsymmetricSigningToken, RequireExpirationTime = false, RequireSignedTokens = false, ValidIssuer = IdentityUtilities.DefaultIssuer, }; // Do not validate audience tokenValidationParameters.ValidateAudience = false; expectedException = ExpectedException.NoExceptionExpected; TestUtilities.ValidateToken(securityToken: samlString, validationParameters: tokenValidationParameters, tokenValidator: tokenHandler, expectedException: expectedException); // no valid audiences tokenValidationParameters.ValidateAudience = true; expectedException = ExpectedException.SecurityTokenInvalidAudienceException("IDX10208"); TestUtilities.ValidateToken(securityToken: samlString, validationParameters: tokenValidationParameters, tokenValidator: tokenHandler, expectedException: expectedException); tokenValidationParameters.ValidateAudience = true; tokenValidationParameters.ValidAudience = "John"; expectedException = new ExpectedException(typeExpected: typeof(SecurityTokenInvalidAudienceException), substringExpected: "IDX10214"); TestUtilities.ValidateToken(securityToken: samlString, validationParameters: tokenValidationParameters, tokenValidator: tokenHandler, expectedException: expectedException); // UriKind.Absolute, no match. tokenValidationParameters.ValidateAudience = true; tokenValidationParameters.ValidAudience = IdentityUtilities.NotDefaultAudience; expectedException = new ExpectedException(typeExpected: typeof(SecurityTokenInvalidAudienceException), substringExpected: "IDX10214"); TestUtilities.ValidateToken(securityToken: samlString, validationParameters: tokenValidationParameters, tokenValidator: tokenHandler, expectedException: expectedException); expectedException = ExpectedException.NoExceptionExpected; tokenValidationParameters.ValidAudience = IdentityUtilities.DefaultAudience; tokenValidationParameters.ValidAudiences = null; TestUtilities.ValidateToken(securityToken: samlString, validationParameters: tokenValidationParameters, tokenValidator: tokenHandler, expectedException: expectedException); // !UriKind.Absolute List<string> audiences = new List<string> { "John", "Paul", "George", "Ringo" }; tokenValidationParameters.ValidAudience = null; tokenValidationParameters.ValidAudiences = audiences; tokenValidationParameters.ValidateAudience = false; expectedException = ExpectedException.NoExceptionExpected; TestUtilities.ValidateToken(securityToken: samlString, validationParameters: tokenValidationParameters, tokenValidator: tokenHandler, expectedException: expectedException); // UriKind.Absolute, no match audiences = new List<string> { "http://www.John.com", "http://www.Paul.com", "http://www.George.com", "http://www.Ringo.com", " " }; tokenValidationParameters.ValidAudience = null; tokenValidationParameters.ValidAudiences = audiences; tokenValidationParameters.ValidateAudience = false; expectedException = ExpectedException.NoExceptionExpected; TestUtilities.ValidateToken(securityToken: samlString, validationParameters: tokenValidationParameters, tokenValidator: tokenHandler, expectedException: expectedException); tokenValidationParameters.ValidateAudience = true; expectedException = new ExpectedException(typeExpected: typeof(SecurityTokenInvalidAudienceException), substringExpected: "IDX10214"); TestUtilities.ValidateToken(securityToken: samlString, validationParameters: tokenValidationParameters, tokenValidator: tokenHandler, expectedException: expectedException); tokenValidationParameters.ValidateAudience = true; expectedException = ExpectedException.NoExceptionExpected; audiences.Add(IdentityUtilities.DefaultAudience); TestUtilities.ValidateToken(securityToken: samlString, validationParameters: tokenValidationParameters, tokenValidator: tokenHandler, expectedException: expectedException); }
public void GetSets() { var samlSecurityTokenHandler = new Saml2SecurityTokenHandler(); var context = new GetSetContext { PropertyNamesAndSetGetValue = new List <KeyValuePair <string, List <object> > > { new KeyValuePair <string, List <object> >("MaximumTokenSizeInBytes", new List <object> { (object)TokenValidationParameters.DefaultMaximumTokenSizeInBytes, (object)1000, (object)10 }), new KeyValuePair <string, List <object> >("SetDefaultTimesOnTokenCreation", new List <object> { true, false, true }), new KeyValuePair <string, List <object> >("TokenLifetimeInMinutes", new List <object> { (object)60, (object)1000, (object)10 }), }, Object = samlSecurityTokenHandler }; TestUtilities.GetSet(context); samlSecurityTokenHandler = new Saml2SecurityTokenHandler(); TestUtilities.SetGet(samlSecurityTokenHandler, "MaximumTokenSizeInBytes", (object)0, ExpectedException.ArgumentOutOfRangeException("IDX10101:"), context); TestUtilities.SetGet(samlSecurityTokenHandler, "MaximumTokenSizeInBytes", (object)1, ExpectedException.NoExceptionExpected, context); TestUtilities.SetGet(samlSecurityTokenHandler, "Serializer", null, ExpectedException.ArgumentNullException(), context); TestUtilities.AssertFailIfErrors("Saml2SecurityTokenHandlerTests_GetSets", context.Errors); }
private void CreateClaims(SamlSecurityToken samlToken, string issuer, TokenValidationParameters validationParameters, PublicSamlSecurityTokenHandler samlSecurityTokenHandler, ExpectedException expectedException) { try { samlSecurityTokenHandler.CreateClaimsPublic(samlToken, issuer, validationParameters ); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } }
public void Constructors() { var context = new CompareContext { Title = "OpenIdConnectConfigurationTests.Constructors" }; RunOpenIdConnectConfigurationTest((string)null, new OpenIdConnectConfiguration(), ExpectedException.ArgumentNullException(), context); RunOpenIdConnectConfigurationTest(OpenIdConfigData.JsonAllValues, OpenIdConfigData.FullyPopulated, ExpectedException.NoExceptionExpected, context); RunOpenIdConnectConfigurationTest(OpenIdConfigData.OpenIdConnectMetatadataBadJson, null, ExpectedException.ArgumentException(substringExpected: "IDX10815:", inner: typeof(JsonReaderException)), context); TestUtilities.AssertFailIfErrors(context); }
/// <summary> /// /// </summary> /// <param name="obj"></param> /// <param name="compareTo"></param> /// <param name="expectedException"></param> /// <param name="asString"> this is useful when passing null for parameter 'is' and 'as' don't contain type info.</param> /// <returns></returns> private JsonWebKeySet RunJsonWebKeySetTest(object obj, JsonWebKeySet compareTo, ExpectedException expectedException, bool asString = true) { JsonWebKeySet jsonWebKeys = null; try { if (obj is string) { jsonWebKeys = new JsonWebKeySet(obj as string); } else if (obj is IDictionary<string, object>) { jsonWebKeys = new JsonWebKeySet(obj as IDictionary<string, object>); } else { if (asString) { jsonWebKeys = new JsonWebKeySet(obj as string); } else { jsonWebKeys = new JsonWebKeySet(obj as IDictionary<string, object>); } } expectedException.ProcessNoException(); } catch (Exception ex) { expectedException.ProcessException(ex); } if (compareTo != null) { Assert.IsTrue(IdentityComparer.AreEqual<JsonWebKeySet>(jsonWebKeys, compareTo, CompareContext.Default), "jsonWebKeys created from: " + (obj == null ? "NULL" : obj.ToString() + " did not match expected.")); } return jsonWebKeys; }
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); } }
public async Task FromJson() { var context = new CompareContext(); var configuration = await GetConfigurationFromMixedAsync(OpenIdConfigData.OpenIdConnectMetadataPingString, expectedException: ExpectedException.NoExceptionExpected); configuration = await GetConfigurationFromMixedAsync(OpenIdConfigData.OpenIdConnectMetadataPingLabsJWKSString, expectedException: ExpectedException.NoExceptionExpected); IdentityComparer.AreEqual(configuration, OpenIdConfigData.PingLabs, context); configuration = await GetConfigurationFromMixedAsync(OpenIdConfigData.JsonAllValues, expectedException: ExpectedException.NoExceptionExpected); IdentityComparer.AreEqual(configuration, OpenIdConfigData.FullyPopulatedWithKeys, context); // jwt_uri is not reachable await GetConfigurationFromTextAsync(OpenIdConfigData.OpenIdConnectMetadataBadUriKeysString, string.Empty, expectedException: ExpectedException.IOException()); // stream is not well formated await GetConfigurationFromTextAsync(OpenIdConfigData.OpenIdConnectMetadataBadFormatString, string.Empty, expectedException: new ExpectedException(typeExpected: typeof(JsonReaderException))); configuration = await GetConfigurationFromMixedAsync(OpenIdConfigData.OpenIdConnectMetadataSingleX509DataString, expectedException: ExpectedException.NoExceptionExpected); IdentityComparer.AreEqual(configuration, OpenIdConfigData.SingleX509Data, context); // dnx 5.0 throws a different exception // 5.0 - Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException // 4.5.1 - System.Security.Cryptography.CryptographicException // for now turn off checking for inner var ee = ExpectedException.InvalidOperationException(inner: typeof(CryptographicException)); ee.IgnoreInnerException = true; await GetConfigurationFromMixedAsync(OpenIdConfigData.OpenIdConnectMetadataBadX509DataString, expectedException: ee); await GetConfigurationFromMixedAsync(OpenIdConfigData.OpenIdConnectMetadataBadBase64DataString, expectedException: ExpectedException.InvalidOperationException(inner: typeof(FormatException))); TestUtilities.AssertFailIfErrors(context); }
public void EmbeddedTokenConstructor1(string testId, JwtSecurityTokenTestVariation outerTokenVariation, JwtSecurityTokenTestVariation innerTokenVariation, string jwt, ExpectedException ee) { JwtSecurityToken outerJwt = null; JwtSecurityToken innerJwt = null; // create inner token try { if (innerTokenVariation != null) { innerJwt = CreateToken(innerTokenVariation); } } catch (Exception ex) { ee.ProcessException(ex); } // create outer token try { if (string.IsNullOrEmpty(jwt)) { outerJwt = new JwtSecurityToken( header: outerTokenVariation.Header, innerToken: innerJwt, rawHeader: outerTokenVariation.RawHeader, rawEncryptedKey: outerTokenVariation.RawEncryptedKey, rawInitializationVector: outerTokenVariation.RawInitializationVector, rawCiphertext: outerTokenVariation.RawCiphertext, rawAuthenticationTag: outerTokenVariation.RawAuthenticationTag); } else { outerJwt = new JwtSecurityToken(jwt); } ee.ProcessNoException(); } catch (Exception ex) { ee.ProcessException(ex); } try { // ensure we can get to every outer token property if (outerJwt != null && (ee == null || ee.TypeExpected == null)) { TestUtilities.CallAllPublicInstanceAndStaticPropertyGets(outerJwt, testId); } if (null != outerTokenVariation.ExpectedJwtSecurityToken) { Assert.True(IdentityComparer.AreEqual(outerTokenVariation.ExpectedJwtSecurityToken, outerJwt)); } } catch (Exception ex) { Assert.True(false, string.Format("Testcase: {0}. UnExpected when getting a properties: '{1}'", outerTokenVariation.Name, ex.ToString())); } try { // ensure we can get to every inner token property if (innerJwt != null && (ee == null || ee.TypeExpected == null)) { TestUtilities.CallAllPublicInstanceAndStaticPropertyGets(innerJwt, testId); } if (null != innerTokenVariation && null != innerTokenVariation.ExpectedJwtSecurityToken) { Assert.True(IdentityComparer.AreEqual(innerTokenVariation.ExpectedJwtSecurityToken, innerJwt)); } } catch (Exception ex) { Assert.True(false, string.Format("Testcase: {0}. UnExpected when getting a properties: '{1}'", testId, ex.ToString())); } try { if (outerJwt != null && innerJwt != null && (ee == null || ee.TypeExpected == null)) { // confirm properties of outer token match our expectation Assert.Equal(outerJwt.InnerToken, innerJwt); CheckPayloadProperties(outerJwt, innerJwt); CheckOuterTokenProperties(outerJwt, outerTokenVariation); } } catch (Exception ex) { Assert.True(false, string.Format("Testcase: {0}. Unexpected inequality between outer and inner token properties: '{1}'", testId, ex.ToString())); } }
public void ContentTypeHeaderParsingTest() { IEnumerable <ContentTypeTestCase> testCases = new ContentTypeTestCase[] { #region Atom test cases new ContentTypeTestCase { // only reading an entry or feed should succeed ContentType = "application/atom+xml;type=feed", ExpectedFormat = ODataFormat.Atom, }, new ContentTypeTestCase { // only reading an entry or feed should succeed ContentType = "application/atom+xml;type=entry", ExpectedFormat = ODataFormat.Atom, }, new ContentTypeTestCase { // reading a feed, an entry, and metadata should succeed ContentType = "application/atom+xml", ExpectedFormat = ODataFormat.Atom, }, new ContentTypeTestCase { // reading a property, an entity reference link, entity reference links, a collection, a service document, and an error should succeed ContentType = "application/xml", ExpectedFormat = ODataFormat.Atom, }, new ContentTypeTestCase { // reading a property, an entity reference link, entity reference links, and a collection should succeed ContentType = "text/xml", ExpectedFormat = ODataFormat.Atom, }, new ContentTypeTestCase { // reading a service document should succeed ContentType = "application/atomsvc+xml", ExpectedFormat = ODataFormat.Atom, }, #endregion Atom test cases #region RawValue test cases new ContentTypeTestCase { // only reading a raw value will succeed ContentType = "text/plain", ExpectedFormat = ODataFormat.RawValue, ShouldSucceedForPayloadKind = pk => pk == ODataPayloadKind.Value || pk == ODataPayloadKind.BinaryValue, }, new ContentTypeTestCase { // only reading a raw value or binary value will succeed; raw values can be read as binary values when the content type is application/octet-stream ContentType = "application/octet-stream", ExpectedFormat = ODataFormat.RawValue, ShouldSucceedForPayloadKind = pk => pk == ODataPayloadKind.Value || pk == ODataPayloadKind.BinaryValue, }, new ContentTypeTestCase { // only raw value / binary value will succeed ContentType = "multipart/mixed", ExpectedFormat = ODataFormat.RawValue, ShouldSucceedForPayloadKind = pk => false, }, new ContentTypeTestCase { // Test for: MimeType allows 0x7F character, but ContentType parsing doesn't ContentType = "application/" + 0x7F, ExpectedFormat = ODataFormat.RawValue, ShouldSucceedForPayloadKind = pk => false, }, #endregion RawValue test cases #region JSON Lite test cases new ContentTypeTestCase { // only batch and raw value will fail (batch payload kind tested separately in BatchContentTypeHeaderParsingTest) ContentType = ApplicationJsonODataLight, ExpectedFormat = ODataFormat.Json, ShouldSucceedForPayloadKind = pk => pk != ODataPayloadKind.Value && pk != ODataPayloadKind.BinaryValue, }, new ContentTypeTestCase { // only batch and raw value will fail (batch payload kind tested separately in BatchContentTypeHeaderParsingTest) ContentType = ApplicationJsonODataLightStreaming, ExpectedFormat = ODataFormat.Json, ShouldSucceedForPayloadKind = pk => pk != ODataPayloadKind.Value && pk != ODataPayloadKind.BinaryValue, }, new ContentTypeTestCase { // only batch and raw value will fail (batch payload kind tested separately in BatchContentTypeHeaderParsingTest) ContentType = ApplicationJsonODataLightNonStreaming, ExpectedFormat = ODataFormat.Json, ShouldSucceedForPayloadKind = pk => pk != ODataPayloadKind.Value && pk != ODataPayloadKind.BinaryValue, }, #endregion JSON Lite test cases #region Error test cases new ContentTypeTestCase { // unsupported content type; everything will fail ContentType = "application/foo", ShouldSucceedForPayloadKind = pk => false, }, new ContentTypeTestCase { // unsupported content type with parameters; everything will fail ContentType = "abc/pqr;a=b;c=d", ShouldSucceedForPayloadKind = pk => false, }, new ContentTypeTestCase { // "image/jpeg" is not supported, even for raw values. ContentType = "image/jpeg", ShouldSucceedForPayloadKind = pk => false, }, #endregion Error test cases #region Content Type is null or empty new ContentTypeTestCase { // null content type and zero content length should be default to Json if the payload kind is not binary value or value. ContentType = null, ContentLength = 0, ExpectedFormat = ODataFormat.Json, ShouldSucceedForPayloadKind = pk => true, ShouldIgnoreTest = pk => pk == ODataPayloadKind.BinaryValue || pk == ODataPayloadKind.Value }, new ContentTypeTestCase { // null content type and zero content length should be default to RawValue if the payload kind is binary value or value. ContentType = null, ContentLength = 0, ExpectedFormat = ODataFormat.RawValue, ShouldSucceedForPayloadKind = pk => true, ShouldIgnoreTest = pk => pk != ODataPayloadKind.Value }, #endregion }; string[] parameters = new string[] { "foo=bar", "foo1=bar1;foo2=bar2" }; testCases = testCases.Concat(testCases.Where(tc => tc.ContentType != null).SelectMany(tc => parameters.Select(p => new ContentTypeTestCase(tc) { ContentType = tc.ContentType + ";" + p }))); int oDataPayloadKindCount = EnumExtensionMethods.GetValues <ODataPayloadKind>().Length; this.Assert.AreEqual(oDataPayloadKindCount, TestReaderUtils.ODataPayloadKinds.Length, "The number of payload kind have changed, please update this test."); IEdmModel model = Microsoft.Test.OData.Utils.Metadata.TestModels.BuildTestModel(); // We don't support batch payloads here; we test those separately in BatchContentTypeHeaderParsingTest IEnumerable <ODataPayloadKind> payloadKinds = TestReaderUtils.ODataPayloadKinds.Where(k => k != ODataPayloadKind.Batch && k != ODataPayloadKind.Unsupported); this.CombinatorialEngineProvider.RunCombinations( testCases, payloadKinds, this.ReaderTestConfigurationProvider.AllFormatConfigurations, (testCase, payloadKind, testConfiguration) => { testConfiguration = new ReaderTestConfiguration(testConfiguration); testConfiguration.MessageReaderSettings.EnableAtom = false; if (IgnoreTestCase(payloadKind, testConfiguration)) { return; } if (testCase.ShouldIgnoreTest != null && testCase.ShouldIgnoreTest(payloadKind)) { return; } string supportedMediaTypes; if (payloadKind == ODataPayloadKind.Value || payloadKind == ODataPayloadKind.BinaryValue) { supportedMediaTypes = TestMediaTypeUtils.GetSupportedMediaTypes(ODataPayloadKind.Value) + ", " + TestMediaTypeUtils.GetSupportedMediaTypes(ODataPayloadKind.BinaryValue); } else { supportedMediaTypes = TestMediaTypeUtils.GetSupportedMediaTypes(payloadKind, /*includeAppJson*/ true); } ExpectedException expectedException = testCase.ExpectedException == null ? testCase.ShouldSucceedForPayloadKind != null && testCase.ShouldSucceedForPayloadKind(payloadKind) ? null : ODataExpectedExceptions.ODataContentTypeException("MediaTypeUtils_CannotDetermineFormatFromContentType", supportedMediaTypes, testCase.ContentType ?? "") : testCase.ExpectedException; // Make sure to run success test cases only in configurations that will work. if (expectedException == null && testConfiguration.Format != null && testCase.ExpectedFormat != testConfiguration.Format) { return; } ODataPayloadElement payloadElement = CreatePayloadElement(model, payloadKind, testConfiguration); // When we write a value with a content type different than 'text/plain', we will read it as binary. // Likewise, when we write a binary value with a 'text/plain' content type, we will read it as a string. Func <ReaderTestConfiguration, ODataPayloadElement> expectedResultElementFunc = null; if (payloadKind == ODataPayloadKind.Value && testCase.ContentType != null && !testCase.ContentType.StartsWith("text/plain")) { expectedResultElementFunc = (testConfig) => ConvertToBinaryPayloadElement(payloadElement); } else if (payloadKind == ODataPayloadKind.BinaryValue && testCase.ContentType != null && testCase.ContentType.StartsWith("text/plain")) { expectedResultElementFunc = (testConfig) => ConvertToStringPayloadElement(payloadElement); } ODataFormat expectedFormat = testCase.ExpectedFormat; ReaderContentTypeTestDescriptor testDescriptor = new ReaderContentTypeTestDescriptor(this.Settings) { PayloadElement = payloadElement, ExpectedResultPayloadElement = expectedResultElementFunc, PayloadEdmModel = model, ExpectedFormat = expectedFormat, ContentType = testCase.ContentType, ExpectedException = expectedException }; testDescriptor.RunTest(testConfiguration); testConfiguration.MessageReaderSettings.EnableAtom = true; }); }
public static TheoryData <string, JwtSecurityTokenTestVariation, JwtSecurityTokenTestVariation, string, ExpectedException> EmbeddedTokenConstructorData() { var dataSet = new TheoryData <string, JwtSecurityTokenTestVariation, JwtSecurityTokenTestVariation, string, ExpectedException>(); dataSet.Add("Embedded token all properties null", // outer token new JwtSecurityTokenTestVariation { RawHeader = null, RawEncryptedKey = null, RawInitializationVector = null, RawCiphertext = null, RawAuthenticationTag = null, }, // inner token new JwtSecurityTokenTestVariation { Issuer = null, Audience = null, Claims = null, SigningCredentials = null, }, String.Empty, ExpectedException.ArgumentNullException() ); JwtSecurityTokenTestVariation innerToken = new JwtSecurityTokenTestVariation { NotBefore = DateTime.MinValue, Expires = DateTime.UtcNow, }; JwtSecurityTokenTestVariation outerValidJweDirect = CreateVariationOnToken(EncodedJwts.ValidJweDirect); dataSet.Add("ValidJweDirect- Construct by parts", outerValidJweDirect, innerToken, String.Empty, ExpectedException.NoExceptionExpected); dataSet.Add("ValidJweDirect- Construct by string", outerValidJweDirect, null, EncodedJwts.ValidJweDirect, ExpectedException.NoExceptionExpected); JwtSecurityTokenTestVariation outerValidJweDirect2 = CreateVariationOnToken(EncodedJwts.ValidJweDirect2); dataSet.Add("ValidJweDirect2- Construct by parts", outerValidJweDirect2, innerToken, String.Empty, ExpectedException.NoExceptionExpected); dataSet.Add("ValidJweDirect2- Construct by string", outerValidJweDirect2, null, EncodedJwts.ValidJweDirect2, ExpectedException.NoExceptionExpected); JwtSecurityTokenTestVariation outerValidJwe = CreateVariationOnToken(EncodedJwts.ValidJwe); dataSet.Add("ValidJwe- Construct by parts", outerValidJwe, innerToken, String.Empty, ExpectedException.NoExceptionExpected); dataSet.Add("ValidJwe- Construct by string", outerValidJwe, null, EncodedJwts.ValidJwe, ExpectedException.NoExceptionExpected); JwtSecurityTokenTestVariation outerValidJwe2 = CreateVariationOnToken(EncodedJwts.ValidJwe2); dataSet.Add("ValidJwe2- Construct by parts", outerValidJwe2, innerToken, String.Empty, ExpectedException.NoExceptionExpected); dataSet.Add("ValidJwe2- Construct by string", outerValidJwe2, null, EncodedJwts.ValidJwe2, ExpectedException.NoExceptionExpected); // Hand in a valid variation. We should fail before the variation is used. dataSet.Add("Invalid outer token 1- Construct by string", outerValidJweDirect, null, EncodedJwts.InvalidJwe, ExpectedException.ArgumentException(substringExpected: "IDX12741")); dataSet.Add("Invalid outer token 2- Construct by string", outerValidJweDirect, null, EncodedJwts.InvalidJwe2, ExpectedException.ArgumentException(substringExpected: "IDX12741")); dataSet.Add("Invalid outer token 3- Construct by string", outerValidJweDirect, null, EncodedJwts.InvalidJwe3, ExpectedException.ArgumentException(substringExpected: "IDX12740")); dataSet.Add("Invalid outer token 4- Construct by string", outerValidJweDirect, null, EncodedJwts.InvalidJwe4, ExpectedException.ArgumentException(substringExpected: "IDX12741")); dataSet.Add("Invalid outer token 5- Construct by string", outerValidJweDirect, null, EncodedJwts.InvalidJwe5, ExpectedException.ArgumentException(substringExpected: "IDX12740")); dataSet.Add("Invalid outer token 6- Construct by string", outerValidJweDirect, null, EncodedJwts.InvalidJwe6, ExpectedException.ArgumentException(substringExpected: "IDX12740")); return(dataSet); }
private void ValidateToken(string securityToken, TokenValidationParameters validationParameters, SecurityTokenHandlerCollection tokenHandlers, ExpectedException expectedException) { try { SecurityToken validatedToken; tokenHandlers.ValidateToken(securityToken, validationParameters, out validatedToken); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } }
public static TheoryData <JwtTheoryData> InvalidRegExSegmentsDataForReadToken(string errorString, TheoryData <JwtTheoryData> theoryData) { var validRegEx = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9"; var invalidRegEx = "eyJpc3MiOiJodHRwOi8vR290Snd0LmNvbSIsImF1Z CI6Imh0"; theoryData.Add(new JwtTheoryData { CanRead = false, TestId = "'invalidRegEx: first position'", Token = invalidRegEx + "." + validRegEx + "." + validRegEx + "." + validRegEx + "." + validRegEx, ExpectedException = ExpectedException.ArgumentException(errorString) }); theoryData.Add(new JwtTheoryData { CanRead = false, TestId = "'invalidRegEx: second position'", Token = validRegEx + "." + invalidRegEx + "." + validRegEx + "." + validRegEx + "." + validRegEx, ExpectedException = ExpectedException.ArgumentException(errorString) }); theoryData.Add(new JwtTheoryData { CanRead = false, TestId = "'invalidRegEx: third position'", Token = validRegEx + "." + validRegEx + "." + invalidRegEx + "." + validRegEx + "." + validRegEx, ExpectedException = ExpectedException.ArgumentException(errorString) }); theoryData.Add(new JwtTheoryData { CanRead = false, TestId = "'invalidRegEx: fourth position'", Token = validRegEx + "." + validRegEx + "." + validRegEx + "." + invalidRegEx + "." + validRegEx, ExpectedException = ExpectedException.ArgumentException(errorString) }); theoryData.Add(new JwtTheoryData { CanRead = false, TestId = "'invalidRegEx: fifth position'", Token = validRegEx + "." + validRegEx + "." + validRegEx + "." + validRegEx + "." + invalidRegEx, ExpectedException = ExpectedException.ArgumentException(errorString) }); theoryData.Add(new JwtTheoryData { CanRead = false, TestId = "'invalidRegEx: first position (dir)'", Token = invalidRegEx + ".." + validRegEx + "." + validRegEx + "." + validRegEx, ExpectedException = ExpectedException.ArgumentException(errorString) }); theoryData.Add(new JwtTheoryData { CanRead = false, TestId = "'invalidRegEx: third position (dir)'", Token = validRegEx + ".." + invalidRegEx + "." + validRegEx + "." + validRegEx, ExpectedException = ExpectedException.ArgumentException(errorString) }); theoryData.Add(new JwtTheoryData { CanRead = false, TestId = "'invalidRegEx: fourth position (dir)'", Token = invalidRegEx + ".." + validRegEx + "." + invalidRegEx + "." + validRegEx, ExpectedException = ExpectedException.ArgumentException(errorString) }); theoryData.Add(new JwtTheoryData { CanRead = false, TestId = "'invalidRegEx: fifth position (dir)'", Token = invalidRegEx + ".." + validRegEx + "." + validRegEx + "." + invalidRegEx, ExpectedException = ExpectedException.ArgumentException(errorString) }); theoryData.Add(new JwtTheoryData { CanRead = false, TestId = "'invalidRegEx: first position (dir, Cipher text missing)'", Token = invalidRegEx + "." + validRegEx + "." + validRegEx, ExpectedException = ExpectedException.ArgumentException(errorString) }); theoryData.Add(new JwtTheoryData { CanRead = false, TestId = "'invalidRegEx: third position (dir, Cipher text missing)'", Token = validRegEx + "." + invalidRegEx + "." + validRegEx, ExpectedException = ExpectedException.ArgumentException(errorString) }); theoryData.Add(new JwtTheoryData { CanRead = false, TestId = "'invalidRegEx: third position (four parts)'", Token = validRegEx + "." + invalidRegEx + ".", ExpectedException = ExpectedException.ArgumentException(errorString) }); theoryData.Add(new JwtTheoryData { CanRead = false, TestId = "'invalidRegEx: fifth position (dir, Cipher text missing)'", Token = validRegEx + "." + validRegEx + "." + invalidRegEx, ExpectedException = ExpectedException.ArgumentException(errorString) }); theoryData.Add(new JwtTheoryData { CanRead = false, TestId = "'Encoding == SignedEncodedJwts.Asymmetric_LocalSts'", Token = "SignedEncodedJwts.Asymmetric_LocalSts", ExpectedException = ExpectedException.ArgumentException(errorString) }); return(theoryData); }
private ClaimsPrincipal RunActorVariation(string secutityToken, string actor, TokenValidationParameters validationParameters, TokenValidationParameters actorValidationParameters, JwtSecurityTokenHandler tokendHandler, ExpectedException expectedException) { ClaimsPrincipal claimsPrincipal = null; try { SecurityToken validatedToken; claimsPrincipal = tokendHandler.ValidateToken(secutityToken, validationParameters, out validatedToken); ClaimsIdentity claimsIdentityValidated = claimsPrincipal.Identity as ClaimsIdentity; ClaimsPrincipal actorClaimsPrincipal = tokendHandler.ValidateToken(actor, actorValidationParameters, out validatedToken); Assert.IsNotNull(claimsIdentityValidated.Actor); Assert.IsTrue(IdentityComparer.AreEqual<ClaimsIdentity>(claimsIdentityValidated.Actor, (actorClaimsPrincipal.Identity as ClaimsIdentity))); expectedException.ProcessNoException(); } catch (Exception ex) { expectedException.ProcessException(ex); } return claimsPrincipal; }
public async Task SetUp() { Repository.ApplyGivenEvents(Given().ToList()); var handler = OnHandler(); try { await handler.Handle(When()); var expected = Expect().ToList(); var published = Repository.Events; CompareEvents(expected, published); } catch (AssertActualExpectedException) //If is an assert exception, throw it to the sky { throw; } catch (Exception exception) //Otherwise should be something expected { if (ExpectedException == null) { Assert.True(false, $"{exception.GetType()}: {exception.Message}\n{exception.StackTrace}"); } Assert.True(exception.GetType() == ExpectedException.GetType(), $"Exception type {exception.GetType()} differs from expected type {ExpectedException.GetType()}"); Assert.True(exception.Message == ExpectedException.Message, $"Exception message \"{exception.Message}\" differs from expected message \"{ExpectedException.GetType()}\""); } }
private bool RunCanReadXmlVariation(XmlReader reader, JwtSecurityTokenHandler tokenHandler,ExpectedException expectedException) { bool retVal = false; try { retVal = tokenHandler.CanReadToken(reader); expectedException.ProcessNoException(); } catch(Exception ex) { expectedException.ProcessException(ex); } return retVal; }
private void GetDocument(string address, IDocumentRetriever docRetriever, CancellationToken token, ExpectedException ee) { try { string doc = docRetriever.GetDocumentAsync(address, token).Result; ee.ProcessNoException(); } catch (AggregateException ex) { ex.Handle((x) => { ee.ProcessException(x); return(true); }); } }
private JwtSecurityToken RunReadXmlVariation(XmlReader reader, JwtSecurityTokenHandler tokenHandler, ExpectedException expectedException) { JwtSecurityToken retVal = null; try { retVal = tokenHandler.ReadToken(reader) as JwtSecurityToken;; expectedException.ProcessNoException(); } catch(Exception ex) { expectedException.ProcessException(ex); } return retVal; }
public void GetDocuments() { FileDocumentRetriever docRetriever = new FileDocumentRetriever(); GetDocument(null, docRetriever, CancellationToken.None, ExpectedException.ArgumentNullException()); GetDocument("OpenIdConnectMetadata.json", docRetriever, CancellationToken.None, ExpectedException.IOException("IDX10804:", typeof(FileNotFoundException), "IDX10814:")); GetDocument("ValidJson.json", docRetriever, CancellationToken.None, ExpectedException.NoExceptionExpected); }
private ClaimsPrincipal RunReadTokenVariation(string securityToken, TokenValidationParameters validationParameters, JwtSecurityTokenHandler tokenHandler, ExpectedException expectedException) { ClaimsPrincipal retVal = null; try { SecurityToken validatedToken; retVal = tokenHandler.ValidateToken(securityToken, validationParameters, out validatedToken); expectedException.ProcessNoException(); } catch (Exception ex) { expectedException.ProcessException(ex); } return retVal; }
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.True(queryString.Contains("bob")); authenticationProtocolMessage.IssuerAddress = string.Empty; queryString = authenticationProtocolMessage.BuildRedirectUrl(); Assert.NotNull(queryString); }
public void JwtSecurityTokenHandler_AudienceValidation() { JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); // "Jwt.Audience == null" TokenValidationParameters validationParameters = new TokenValidationParameters() { ValidateIssuer = false, RequireExpirationTime = false, RequireSignedTokens = false }; ExpectedException ee = new ExpectedException(typeof(SecurityTokenInvalidAudienceException), substringExpected: "IDX10208"); string jwt = (tokenHandler.CreateToken(issuer: "http://www.GotJwt.com", audience: null) as JwtSecurityToken).RawData; TestUtilities.ValidateToken(jwt, validationParameters, tokenHandler, ee); // "jwt.Audience == EmptyString" ee = new ExpectedException(typeof(SecurityTokenInvalidAudienceException), substringExpected: "IDX10208"); jwt = (tokenHandler.CreateToken(issuer: "http://www.GotJwt.com", audience: string.Empty) as JwtSecurityToken).RawData; TestUtilities.ValidateToken(jwt, validationParameters, tokenHandler, ee); // "jwt.Audience == whitespace" ee = new ExpectedException(typeof(SecurityTokenInvalidAudienceException), substringExpected: "IDX10208"); jwt = (tokenHandler.CreateToken(issuer: "http://www.GotJwt.com", audience: " ") as JwtSecurityToken).RawData; TestUtilities.ValidateToken(jwt, validationParameters, tokenHandler, ee); // "TokenValidationParameters.ValidAudience TokenValidationParameters.ValidAudiences both null" ee = new ExpectedException(typeof(SecurityTokenInvalidAudienceException), substringExpected: "IDX10208"); jwt = (tokenHandler.CreateToken(issuer: "http://www.GotJwt.com", audience: "http://www.GotJwt.com") as JwtSecurityToken).RawData; TestUtilities.ValidateToken(jwt, validationParameters, tokenHandler, ee); // "TokenValidationParameters.ValidAudience empty, TokenValidationParameters.ValidAudiences empty" ee = new ExpectedException(typeof(SecurityTokenInvalidAudienceException), substringExpected: "IDX10214"); jwt = (tokenHandler.CreateToken(issuer: "http://www.GotJwt.com", audience: "http://www.GotJwt.com") as JwtSecurityToken).RawData; validationParameters = new TokenValidationParameters() { RequireExpirationTime = false, RequireSignedTokens = false, ValidAudience = string.Empty, ValidAudiences = new List<string>(), ValidateIssuer = false }; TestUtilities.ValidateToken(jwt, validationParameters, tokenHandler, ee); // "TokenValidationParameters.ValidAudience whitespace, TokenValidationParameters.ValidAudiences empty" ee = new ExpectedException(typeof(SecurityTokenInvalidAudienceException), substringExpected: "IDX10214"); jwt = (tokenHandler.CreateToken(issuer: "http://www.GotJwt.com", audience: "http://www.GotJwt.com") as JwtSecurityToken).RawData; validationParameters = new TokenValidationParameters() { RequireExpirationTime = false, RequireSignedTokens = false, ValidAudience = " ", ValidAudiences = new List<string>(), ValidateIssuer = false }; TestUtilities.ValidateToken(jwt, validationParameters, tokenHandler, ee); // "TokenValidationParameters.ValidAudience empty, TokenValidationParameters.ValidAudience one null string" ee = new ExpectedException(typeof(SecurityTokenInvalidAudienceException), substringExpected: "IDX10214"); jwt = (tokenHandler.CreateToken(issuer: "http://www.GotJwt.com", audience: "http://www.GotJwt.com") as JwtSecurityToken).RawData; validationParameters = new TokenValidationParameters() { RequireExpirationTime = false, RequireSignedTokens = false, ValidAudience = "", ValidAudiences = new List<string>() { null }, ValidateIssuer = false }; TestUtilities.ValidateToken(jwt, validationParameters, tokenHandler, ee); // "TokenValidationParameters.ValidAudience empty, TokenValidationParameters.ValidAudiences one empty string" ee = new ExpectedException(typeof(SecurityTokenInvalidAudienceException), substringExpected: "IDX10214"); jwt = (tokenHandler.CreateToken(issuer: "http://www.GotJwt.com", audience: "http://www.GotJwt.com") as JwtSecurityToken).RawData; validationParameters = new TokenValidationParameters() { RequireExpirationTime = false, RequireSignedTokens = false, ValidAudience = "", ValidAudiences = new List<string>() { string.Empty }, ValidateIssuer = false }; TestUtilities.ValidateToken(jwt, validationParameters, tokenHandler, ee); // "TokenValidationParameters.ValidAudience string.Empty, TokenValidationParameters.ValidAudiences one string whitespace" ee = new ExpectedException(typeof(SecurityTokenInvalidAudienceException), substringExpected: "IDX10214"); jwt = (tokenHandler.CreateToken(issuer: "http://www.GotJwt.com", audience: "http://www.GotJwt.com") as JwtSecurityToken).RawData; validationParameters = new TokenValidationParameters() { RequireExpirationTime = false, RequireSignedTokens = false, ValidAudience = "", ValidAudiences = new List<string>() { " " }, ValidateIssuer = false }; TestUtilities.ValidateToken(jwt, validationParameters, tokenHandler, ee); validationParameters.AudienceValidator = (aud, token, tvp) => { return false; }; ee = new ExpectedException(typeExpected: typeof(SecurityTokenInvalidAudienceException), substringExpected: "IDX10231:"); TestUtilities.ValidateToken(jwt, validationParameters, tokenHandler, ee); validationParameters.ValidateAudience = false; validationParameters.AudienceValidator = IdentityUtilities.AudienceValidatorThrows; TestUtilities.ValidateToken(securityToken: jwt, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: ExpectedException.NoExceptionExpected); }
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 bool CanReadToken(string securityToken, SamlSecurityTokenHandler samlSecurityTokenHandler, ExpectedException expectedException) { bool canReadToken = false; try { canReadToken = samlSecurityTokenHandler.CanReadToken(securityToken); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } return canReadToken; }
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 ValidateAudience() { SamlSecurityTokenHandler tokenHandler = new SamlSecurityTokenHandler(); ExpectedException expectedException; string samlString = IdentityUtilities.CreateSamlToken(); TokenValidationParameters validationParameters = new TokenValidationParameters { ValidIssuer = IdentityUtilities.DefaultIssuer, IssuerSigningToken = IdentityUtilities.DefaultAsymmetricSigningToken, }; // Do not validate audience validationParameters.ValidateAudience = false; expectedException = ExpectedException.NoExceptionExpected; TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: ExpectedException.NoExceptionExpected); validationParameters.ValidateAudience = true; expectedException = ExpectedException.SecurityTokenInvalidAudienceException(); TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); validationParameters.ValidateAudience = true; validationParameters.ValidAudience = "John"; expectedException = ExpectedException.SecurityTokenInvalidAudienceException(substringExpected: "IDX10214:"); TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); // UriKind.Absolute, no match. validationParameters.ValidateAudience = true; validationParameters.ValidAudience = IdentityUtilities.NotDefaultAudience; expectedException = ExpectedException.SecurityTokenInvalidAudienceException(substringExpected: "IDX10214:"); TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); expectedException = ExpectedException.NoExceptionExpected; validationParameters.ValidAudience = IdentityUtilities.DefaultAudience; validationParameters.ValidAudiences = null; TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); // !UriKind.Absolute List<string> audiences = new List<string> { "John", "Paul", "George", "Ringo" }; validationParameters.ValidAudience = null; validationParameters.ValidAudiences = audiences; validationParameters.ValidateAudience = false; expectedException = ExpectedException.NoExceptionExpected; TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); // UriKind.Absolute, no match audiences = new List<string> { "http://www.John.com", "http://www.Paul.com", "http://www.George.com", "http://www.Ringo.com", " " }; validationParameters.ValidAudience = null; validationParameters.ValidAudiences = audiences; validationParameters.ValidateAudience = false; expectedException = ExpectedException.NoExceptionExpected; TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); validationParameters.ValidateAudience = true; expectedException = ExpectedException.SecurityTokenInvalidAudienceException(substringExpected: "IDX10214"); TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); validationParameters.ValidateAudience = true; expectedException = ExpectedException.NoExceptionExpected; audiences.Add(IdentityUtilities.DefaultAudience); TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); validationParameters.AudienceValidator = (aud, token, tvp) => { return false; }; expectedException = new ExpectedException(typeExpected: typeof(SecurityTokenInvalidAudienceException), substringExpected: "IDX10231:"); TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); validationParameters.ValidateAudience = false; validationParameters.AudienceValidator = IdentityUtilities.AudienceValidatorThrows; TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: ExpectedException.NoExceptionExpected); }
private async Task<OpenIdConnectConfiguration> GetConfigurationFromMixedAsync(string primaryDocument, ExpectedException expectedException, OpenIdConnectConfiguration expectedConfiguration = null) { OpenIdConnectConfiguration openIdConnectConfiguration = null; try { openIdConnectConfiguration = await OpenIdConnectConfigurationRetriever.GetAsync( new TestDocumentRetriever(primaryDocument, new GenericDocumentRetriever()), "primary", CancellationToken.None); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } if (expectedConfiguration != null) { Assert.IsTrue(IdentityComparer.AreEqual(openIdConnectConfiguration, expectedConfiguration)); } return openIdConnectConfiguration; }
/// <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) { Assert.IsNotNull(obj, "'obj' can not be null"); Assert.IsFalse(string.IsNullOrWhiteSpace(property), "'property' can not be null or whitespace"); Type type = obj.GetType(); PropertyInfo propertyInfo = type.GetProperty(property); Assert.IsNotNull(propertyInfo, "'get is not found for property: '" + property + "', type: '" + type.ToString() + "'"); Assert.IsTrue(propertyInfo.CanWrite, "can not write to property: '" + property + "', type: '" + type.ToString() + "'"); try { propertyInfo.SetValue(obj, propertyValue); object retval = propertyInfo.GetValue(obj); Assert.AreEqual(propertyValue, retval); expectedException.ProcessNoException(); } catch (Exception exception) { // pass inner exception expectedException.ProcessException(exception.InnerException); } }
public void GetPayloadValues() { var context = new CompareContext(); TestUtilities.WriteHeader($"{this}.GetPayloadValues"); var token = new JsonWebToken("{}", jObject); var intarray = token.GetPayloadValue <int[]>("intarray"); IdentityComparer.AreEqual(new int[] { 1, 2, 3 }, intarray, context); var array = token.GetPayloadValue <object[]>("array"); IdentityComparer.AreEqual(new object[] { 1L, "2", 3L }, array, context); // only possible internally within the library since we're using Microsoft.IdentityModel.Json.Linq.JObject var jobject = token.GetPayloadValue <JObject>("jobject"); IdentityComparer.AreEqual(JObject.Parse(@"{ ""string1"":""string1value"", ""string2"":""string2value"" }"), jobject, context); var name = token.GetPayloadValue <string>("string"); IdentityComparer.AreEqual("bob", name, context); var floatingPoint = token.GetPayloadValue <float>("float"); IdentityComparer.AreEqual(42.0, floatingPoint, context); var integer = token.GetPayloadValue <int>("integer"); IdentityComparer.AreEqual(42, integer, context); var nill = token.GetPayloadValue <object>("nill"); IdentityComparer.AreEqual(nill, null, context); var boolean = token.GetPayloadValue <bool>("bool"); IdentityComparer.AreEqual(boolean, true, context); var dateTimeValue = token.GetPayloadValue <string>("dateTime"); IdentityComparer.AreEqual(dateTimeValue, dateTime.ToString(), context); var dateTimeIso8061Value = token.GetPayloadValue <DateTime>("dateTimeIso8061"); IdentityComparer.AreEqual(dateTimeIso8061Value, dateTime, context); try // Try to retrieve a value that doesn't exist in the header. { token.GetPayloadValue <int>("doesnotexist"); } catch (Exception ex) { ExpectedException.ArgumentException("IDX14304:").ProcessException(ex, context); } try // Try to retrieve an integer when the value is actually a string. { token.GetPayloadValue <int>("string"); } catch (Exception ex) { ExpectedException.ArgumentException("IDX14305:", typeof(System.FormatException)).ProcessException(ex, context); } TestUtilities.AssertFailIfErrors(context); }
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 async Task FromFile() { var context = new CompareContext(); var configuration = await GetConfigurationAsync(OpenIdConfigData.JsonFile, ExpectedException.NoExceptionExpected, OpenIdConfigData.FullyPopulatedWithKeys, context); // jwt_uri points to bad formated JSON configuration = await GetConfigurationAsync(OpenIdConfigData.JsonWebKeySetBadUriFile, ExpectedException.IOException(inner: typeof(FileNotFoundException)), null, context); // reading form a file that does not exist configuration = await GetConfigurationAsync("FileDoesNotExist.json", ExpectedException.IOException(inner: typeof(FileNotFoundException)), null, context); TestUtilities.AssertFailIfErrors(context); }
private async Task<OpenIdConnectConfiguration> GetConfigurationAsync(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.IsTrue(IdentityComparer.AreEqual(openIdConnectConfiguration, expectedConfiguration)); } return openIdConnectConfiguration; }
public BatchWriterTestDescriptor(Settings settings, InvocationAndOperationDescriptor[] invocationsAndOperationDescriptors, int?maxPartsPerBatch, int?maxOperationsPerChangeset, ExpectedException expectedException) { ExceptionUtilities.CheckArgumentNotNull(expectedException, "expectedExceptionMessage"); this.TestDescriptorSettings = settings; this.invocationsAndOperationDescriptors = invocationsAndOperationDescriptors; this.expectedResultCallback = CreateExpectedErrorResultCallback(null, null, expectedException, this.TestDescriptorSettings.ExpectedResultSettings); this.maxPartsPerBatch = maxPartsPerBatch; this.maxOperationsPerChangeset = maxOperationsPerChangeset; }
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 async Task FromNetwork() { OpenIdConnectConfiguration configuration = await GetConfigurationFromHttpAsync(OpenIdConfigData.AADCommonUrl, expectedException: ExpectedException.NoExceptionExpected); Assert.NotNull(configuration); await GetConfigurationFromHttpAsync(string.Empty, expectedException: ExpectedException.ArgumentNullException()); await GetConfigurationFromHttpAsync(OpenIdConfigData.BadUri, expectedException: ExpectedException.ArgumentException("IDX20108:")); await GetConfigurationFromHttpAsync(OpenIdConfigData.HttpsBadUri, expectedException: ExpectedException.IOException(inner: typeof(HttpRequestException))); }