public void SerializesCustomProperties()
        {
            var originalInnerException = new AssertException("User Message");
            var originalException = new AfterTestException(originalInnerException);

            var deserializedException = SerializationUtility.SerializeAndDeserialize(originalException);

            var deserializedInnerException = Assert.Single(deserializedException.AfterExceptions);
            Assert.Equal(originalInnerException.Message, deserializedInnerException.Message);
            var deserializedAssertException = Assert.IsType<AssertException>(deserializedInnerException);
            Assert.Equal(originalInnerException.UserMessage, deserializedAssertException.UserMessage);
        }
示例#2
0
        void TraceRidges(BinaryMap binary, Dictionary <Point, SkeletonBuilder.Minutia> minutiaePoints)
        {
            Dictionary <Point, SkeletonBuilder.Ridge> leads = new Dictionary <Point, SkeletonBuilder.Ridge>();

            foreach (Point minutiaPoint in minutiaePoints.Keys)
            {
                foreach (Point startRelative in Neighborhood.CornerNeighbors)
                {
                    Point start = Calc.Add(minutiaPoint, startRelative);
                    if (binary.GetBitSafe(start, false) && !minutiaePoints.ContainsKey(start) && !leads.ContainsKey(start))
                    {
                        SkeletonBuilder.Ridge ridge = new SkeletonBuilder.Ridge();
                        ridge.Points.Add(minutiaPoint);
                        ridge.Points.Add(start);
                        Point previous = minutiaPoint;
                        Point current  = start;
                        do
                        {
                            Point next = new Point();
                            foreach (Point nextRelative in Neighborhood.CornerNeighbors)
                            {
                                next = Calc.Add(current, nextRelative);
                                if (binary.GetBitSafe(next, false) && next != previous)
                                {
                                    break;
                                }
                            }
                            AssertException.Check(next != new Point());
                            previous = current;
                            current  = next;
                            ridge.Points.Add(current);
                        } while (!minutiaePoints.ContainsKey(current));
                        Point end = current;

                        ridge.Start                     = minutiaePoints[minutiaPoint];
                        ridge.End                       = minutiaePoints[end];
                        leads[ridge.Points[1]]          = ridge;
                        leads[ridge.Reversed.Points[1]] = ridge;
                    }
                }
            }
        }
        public async Task MexEndpointFailsToResolveTestAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddInstanceDiscoveryMockHandler();
                AddMockHandlerDefaultUserRealmDiscovery(httpManager);

                // MEX
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedUrl     = "https://msft.sts.microsoft.com/adfs/services/trust/mex",
                    ExpectedMethod  = HttpMethod.Get,
                    ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent(
                            File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("TestMex.xml"))
                            .Replace("<wsp:All>", " "))
                    }
                });

                PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                              .WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs)
                                              .WithHttpManager(httpManager)
                                              .WithTelemetry(new TraceTelemetryConfig())
                                              .BuildConcrete();

                // Call acquire token, Mex parser fails
                MsalClientException result = await AssertException.TaskThrowsAsync <MsalClientException>(
                    async() => await app.AcquireTokenByUsernamePassword(
                        TestConstants.s_scope,
                        TestConstants.s_user.Username,
                        _secureString).ExecuteAsync(CancellationToken.None).ConfigureAwait(false)).ConfigureAwait(false);

                // Check exception message
                Assert.AreEqual(MsalErrorMessage.ParsingMetadataDocumentFailed, result.Message);
                Assert.AreEqual("parsing_ws_metadata_exchange_failed", result.ErrorCode);

                // There should be no cached entries.
                Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count());
            }
        }
        public async Task AcquireTokenByIntegratedWindowsAuthInvalidClientTestAsync()
        {
            IDictionary <string, string> extraQueryParamsAndClaims =
                TestConstants.ExtraQueryParameters.ToDictionary(e => e.Key, e => e.Value);

            extraQueryParamsAndClaims.Add(OAuth2Parameter.Claims, TestConstants.Claims);

            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddInstanceDiscoveryMockHandler();

                MockHttpMessageHandler realmDiscoveryHandler = AddMockHandlerDefaultUserRealmDiscovery(httpManager);
                AddMockHandlerMex(httpManager);
                AddMockHandlerWsTrustWindowsTransport(httpManager);
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedUrl     = "https://login.microsoftonline.com/common/oauth2/v2.0/token",
                    ExpectedMethod  = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateInvalidClientResponseMessage()
                });

                PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                              .WithAuthority(new Uri(ClientApplicationBase.DefaultAuthority), true)
                                              .WithHttpManager(httpManager)
                                              .WithExtraQueryParameters(TestConstants.ExtraQueryParameters)
                                              .WithTelemetry(new TraceTelemetryConfig())
                                              .BuildConcrete();

                MsalServiceException result = await AssertException.TaskThrowsAsync <MsalServiceException>(
                    async() => await app.AcquireTokenByIntegratedWindowsAuth(TestConstants.s_scope)
                    .WithClaims(TestConstants.Claims)
                    .WithUsername(TestConstants.s_user.Username)
                    .ExecuteAsync().ConfigureAwait(false)).ConfigureAwait(false);

                // Check inner exception
                Assert.AreEqual(MsalError.InvalidClient, result.ErrorCode);

                // There should be no cached entries.
                Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count());
            }
        }
示例#5
0
        public async Task PopWhenBrokerIsNotAvailableTest_Async()
        {
            //MSAL should not fall back to using the browser if the broker is not available when using POP
            // Arrange
            using (var harness = CreateTestHarness())
            {
                harness.HttpManager.AddInstanceDiscoveryMockHandler();

                var mockBroker = Substitute.For <IBroker>();
                mockBroker.IsBrokerInstalledAndInvokable(AuthorityType.Aad).Returns(false);
                mockBroker.IsPopSupported.Returns(true);

                var pca = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                          .WithExperimentalFeatures(true)
                          .WithBrokerPreview()
                          .WithTestBroker(mockBroker)
                          .WithHttpManager(harness.HttpManager)
                          .BuildConcrete();

                pca.ServiceBundle.Config.BrokerCreatorFunc = (x, y, z) => mockBroker;

                pca.ServiceBundle.ConfigureMockWebUI();
                harness.HttpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedMethod  = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(
                        "user.read",
                        MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
                        MockHelpers.CreateClientInfo(TestConstants.Uid, TestConstants.Utid))
                });

                // Act
                var exception = await AssertException.TaskThrowsAsync <MsalClientException>(async() => { await pca.AcquireTokenInteractive(TestConstants.s_graphScopes)
                                                                                                         .WithProofOfPossession(TestConstants.Nonce, HttpMethod.Get, new Uri(TestConstants.AuthorityCommonTenant))
                                                                                                         .ExecuteAsync()
                                                                                                         .ConfigureAwait(false); }).ConfigureAwait(false);

                Assert.AreEqual(MsalError.BrokerApplicationRequired, exception.ErrorCode);
                Assert.AreEqual(MsalErrorMessage.CannotInvokeBrokerForPop, exception.Message);
            }
        }
        public async Task AcquireTokenSilent_Account_NoHomeAccountIDAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                              .WithAuthority(new Uri(TestConstants.AuthorityTestTenant), true)
                                              .WithHttpManager(httpManager)
                                              .BuildConcrete();

                TokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor);

                var exception = await AssertException.TaskThrowsAsync <MsalUiRequiredException>(() => app.AcquireTokenSilent(
                                                                                                    TestConstants.s_scope.ToArray(),
                                                                                                    new Account(null, null, null))
                                                                                                .ExecuteAsync()).ConfigureAwait(false);

                Assert.AreEqual(MsalError.NoTokensFoundError, exception.ErrorCode);
                Assert.AreEqual(UiRequiredExceptionClassification.AcquireTokenSilentFailed, exception.Classification);
            }
        }
示例#7
0
        public async Task PopWhenBrokerIsNotEnabledForATS_Async()
        {
            // Arrange
            var pca = PublicClientApplicationBuilder
                      .Create(TestConstants.ClientId)
                      .WithExperimentalFeatures()
                      .BuildConcrete();

            // Act

            MsalClientException ex = await AssertException.TaskThrowsAsync <MsalClientException>(async() =>
                                                                                                 await pca.AcquireTokenSilent(TestConstants.s_graphScopes, TestConstants.LocalAccountId)
                                                                                                 .WithProofOfPossession(TestConstants.Nonce, HttpMethod.Get, new Uri(TestConstants.AuthorityCommonTenant))
                                                                                                 .ExecuteAsync()
                                                                                                 .ConfigureAwait(false))
                                     .ConfigureAwait(false);

            Assert.AreEqual(MsalError.BrokerRequiredForPop, ex.ErrorCode);
            Assert.AreEqual(MsalErrorMessage.BrokerRequiredForPop, ex.Message);
        }
        public void NullArgsTest()
        {
            using (var harness = CreateTestHarness())
            {
                Uri                            uri               = new Uri("https://www.contoso.com/path1/path2?queryParam1=a&queryParam2=b");
                HttpMethod                     method            = HttpMethod.Post;
                HttpRequestMessage             httpRequest       = new HttpRequestMessage(method, uri);
                var                            popCryptoProvider = Substitute.For <IPoPCryptoProvider>();
                PoPAuthenticationConfiguration config            = null;

                AssertException.Throws <ArgumentNullException>(() => new PopAuthenticationScheme(config, harness.ServiceBundle));

                config = new PoPAuthenticationConfiguration(uri);
                config.PopCryptoProvider = new InMemoryCryptoProvider();

                AssertException.Throws <ArgumentNullException>(() => new PopAuthenticationScheme(config, null));
                AssertException.Throws <ArgumentNullException>(() => new PoPAuthenticationConfiguration((HttpRequestMessage)null));
                AssertException.Throws <ArgumentNullException>(() => new PoPAuthenticationConfiguration((Uri)null));
            }
        }
示例#9
0
        public void AdalClaimsChallengeExceptionThrownWithAcquireTokenClientCredentialUserAssertionWhenClaimsChallengeRequiredTestAsync()
        {
            var    context     = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, new TokenCache());
            var    credential  = new ClientCredential(TestConstants.DefaultClientId, TestConstants.DefaultClientSecret);
            string accessToken = "some-access-token";

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler()
            {
                Method          = HttpMethod.Post,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent(responseContent)
                }
            });

            var result = AssertException.TaskThrows <AdalClaimChallengeException>(() =>
                                                                                  context.AcquireTokenAsync(TestConstants.DefaultResource, credential, new UserAssertion(accessToken)));

            Assert.AreEqual(claims.Replace("\\", ""), result.Claims);
        }
示例#10
0
        public async Task HttpRequestExceptionIsNotSuppressedAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddInstanceDiscoveryMockHandler();

                var app = ConfidentialClientApplicationBuilder.Create(MsalTestConstants.ClientId)
                          .WithAuthority(new Uri(ClientApplicationBase.DefaultAuthority), true)
                          .WithRedirectUri(MsalTestConstants.RedirectUri)
                          .WithClientSecret(MsalTestConstants.ClientSecret)
                          .WithHttpManager(httpManager)
                          .BuildConcrete();

                // add mock response bigger than 1MB for Http Client
                httpManager.AddFailingRequest(new InvalidOperationException());

                await AssertException.TaskThrowsAsync <InvalidOperationException>(
                    () => app.AcquireTokenForClient(MsalTestConstants.Scope.ToArray()).ExecuteAsync(CancellationToken.None)).ConfigureAwait(false);
            }
        }
示例#11
0
        public void TestCreateSameName()
        {
            var ownerId = Guid.NewGuid();
            var search  = new JobAdSearch
            {
                Criteria = CreateCriteria(0),
                Name     = SearchName,
            };

            _jobAdSearchesCommand.CreateJobAdSearch(ownerId, search);

            // Create another.

            search = new JobAdSearch
            {
                Criteria = CreateCriteria(0),
                Name     = SearchName,
            };
            AssertException.Thrown <ValidationErrorsException>(() => _jobAdSearchesCommand.CreateJobAdSearch(ownerId, search), "A 'LinkMe.Framework.Utility.Validation.DuplicateValidationError' error has occurred for the Name property.");
        }
        public void ArgNull()
        {
            AssertException.Throws <ArgumentNullException>(() => new MsalRefreshTokenCacheKey("", "clientId", "uid", "1"));
            AssertException.Throws <ArgumentNullException>(() => new MsalRefreshTokenCacheKey(null, "clientId", "uid", "1"));
            AssertException.Throws <ArgumentNullException>(() => new MsalRefreshTokenCacheKey(null, "clientId", "uid", "1"));
            AssertException.Throws <ArgumentNullException>(() => new MsalRefreshTokenCacheKey("env", null, "uid", "1"));

            AssertException.Throws <ArgumentNullException>(() => new MsalIdTokenCacheKey("", "tid", "uid", "cid"));
            AssertException.Throws <ArgumentNullException>(() => new MsalIdTokenCacheKey(null, "tid", "uid", "cid"));
            AssertException.Throws <ArgumentNullException>(() => new MsalIdTokenCacheKey("env", "tid", "uid", ""));
            AssertException.Throws <ArgumentNullException>(() => new MsalIdTokenCacheKey("env", "tid", "uid", null));

            AssertException.Throws <ArgumentNullException>(() => new MsalAccessTokenCacheKey("", "tid", "uid", "cid", "scopes"));
            AssertException.Throws <ArgumentNullException>(() => new MsalAccessTokenCacheKey(null, "tid", "uid", "cid", "scopes"));
            AssertException.Throws <ArgumentNullException>(() => new MsalAccessTokenCacheKey("env", "tid", "uid", "", "scopes"));
            AssertException.Throws <ArgumentNullException>(() => new MsalAccessTokenCacheKey("env", "tid", "uid", null, "scopes"));

            AssertException.Throws <ArgumentNullException>(() => new MsalAccountCacheKey("", "tid", "uid", "localid", "aad"));
            AssertException.Throws <ArgumentNullException>(() => new MsalAccountCacheKey(null, "tid", "uid", "localid", "msa"));
        }
        public async Task AcquireTokenSilent_LoginHint_NoAccountAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                PublicClientApplication app = PublicClientApplicationBuilder.Create(MsalTestConstants.ClientId)
                                              .WithAuthority(new Uri(MsalTestConstants.AuthorityTestTenant), true)
                                              .WithHttpManager(httpManager)
                                              .WithTelemetry(new TraceTelemetryConfig())
                                              .BuildConcrete();
                _tokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor);

                var exception = await AssertException.TaskThrowsAsync <MsalUiRequiredException>(() => app.AcquireTokenSilent(
                                                                                                    MsalTestConstants.Scope.ToArray(),
                                                                                                    "*****@*****.**")
                                                                                                .WithAuthority(app.Authority, false)
                                                                                                .ExecuteAsync()).ConfigureAwait(false);

                Assert.AreEqual(MsalError.NoAccountForLoginHint, exception.ErrorCode);
            }
        }
示例#14
0
        public void AdalClaimsChallengeExceptionThrownWithClientAssertionWhenClaimsChallengeRequiredTestAsync()
        {
            var certificate     = new X509Certificate2("valid_cert.pfx", TestConstants.DefaultPassword);
            var clientAssertion = new ClientAssertionCertificate(TestConstants.DefaultClientId, certificate);
            var context         = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, new TokenCache());

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler()
            {
                Method          = HttpMethod.Post,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent(responseContent)
                }
            });

            var result = AssertException.TaskThrows <AdalClaimChallengeException>(() =>
                                                                                  context.AcquireTokenAsync(TestConstants.DefaultResource, clientAssertion));

            Assert.AreEqual(claims.Replace("\\", ""), result.Claims);
        }
        public async Task ROPC_MSA_Async()
        {
            var labResponse = await LabUserHelper.GetMsaUserAsync().ConfigureAwait(false);

            SecureString securePassword = new NetworkCredential("", labResponse.User.GetOrFetchPassword()).SecurePassword;

            var msalPublicClient = PublicClientApplicationBuilder
                                   .Create(labResponse.App.AppId)
                                   .WithAuthority(Authority)
                                   .Build();

            var result = await AssertException.TaskThrowsAsync <MsalClientException>(() =>
                                                                                     msalPublicClient
                                                                                     .AcquireTokenByUsernamePassword(s_scopes, labResponse.User.Upn, securePassword)
                                                                                     .ExecuteAsync(CancellationToken.None))
                         .ConfigureAwait(false);

            Assert.AreEqual(MsalError.RopcDoesNotSupportMsaAccounts, result.ErrorCode);
            Assert.AreEqual(MsalErrorMessage.RopcDoesNotSupportMsaAccounts, result.Message);
        }
        public void TestPluginSelection()
        {
            var ex = AssertException.Throws <MsalClientException>(
                () => _wamBroker.IsMsaRequestAsync(Authority.CreateAuthority(TestConstants.B2CAuthority), null, false).GetAwaiter().GetResult());

            Assert.AreEqual(MsalError.WamNoB2C, ex.ErrorCode);

            Assert.IsFalse(
                _wamBroker.IsMsaRequestAsync(Authority.CreateAuthority(TestConstants.ADFSAuthority), null, false).Result,
                "ADFS authorities should be handled by AAD plugin");

            Assert.IsTrue(
                _wamBroker.IsMsaRequestAsync(Authority.CreateAuthority(TestConstants.AuthorityCommonTenant), TestConstants.MsaTenantId, false).Result,
                "Common authority - look at account tenant ID to determine plugin");

            Assert.IsFalse(
                _wamBroker.IsMsaRequestAsync(Authority.CreateAuthority(TestConstants.AuthorityCommonTenant), TestConstants.TenantId, false).Result,
                "Common authority - look at account tenant ID to determine plugin");



            Assert.IsFalse(
                _wamBroker.IsMsaRequestAsync(Authority.CreateAuthority(TestConstants.AuthorityOrganizationsTenant), TestConstants.TenantId, false).Result,
                "Organizations authority - AAD plugin unless MSA-pt");

            Assert.IsFalse(
                _wamBroker.IsMsaRequestAsync(Authority.CreateAuthority(TestConstants.AuthorityOrganizationsTenant), TestConstants.TenantId, true).Result,
                "Organizations authority with MSA-pt - based on home account id");

            Assert.IsTrue(
                _wamBroker.IsMsaRequestAsync(Authority.CreateAuthority(TestConstants.AuthorityOrganizationsTenant), TestConstants.MsaTenantId, true).Result,
                "Organizations authority with MSA-pt - based on home account id");

            Assert.IsTrue(
                _wamBroker.IsMsaRequestAsync(Authority.CreateAuthority(TestConstants.AuthorityConsumersTenant), TestConstants.TenantId, false).Result,
                "Consumer authority - msa plugin");

            Assert.IsFalse(
                _wamBroker.IsMsaRequestAsync(Authority.CreateAuthority(TestConstants.AuthorityGuidTenant), TestConstants.TenantId, true).Result,
                "Tenanted authorities - AAD plugin");
        }
示例#17
0
        public void ConcurrentDictionary_TestIDictionary_Negative()
        {
            IDictionary dictionary = new ConcurrentDictionary <string, int>();

            AssertException.Throws <ArgumentNullException>(
                () => dictionary.Add(null, 1));
            // "TestIDictionary:  FAILED.  Add didn't throw ANE when null key is passed");

            AssertException.Throws <ArgumentException>(
                () => dictionary.Add(1, 1));
            // "TestIDictionary:  FAILED.  Add didn't throw AE when incorrect key type is passed");

            AssertException.Throws <ArgumentException>(
                () => dictionary.Add("1", "1"));
            // "TestIDictionary:  FAILED.  Add didn't throw AE when incorrect value type is passed");

            AssertException.Throws <ArgumentNullException>(
                () => dictionary.Contains(null));
            // "TestIDictionary:  FAILED.  Contain didn't throw ANE when null key is passed");

            //Test Remove
            AssertException.Throws <ArgumentNullException>(
                () => dictionary.Remove(null));
            // "TestIDictionary:  FAILED.  Remove didn't throw ANE when null key is passed");

            //Test this[]
            AssertException.Throws <ArgumentNullException>(
                () => { object val = dictionary[null]; });
            // "TestIDictionary:  FAILED.  this[] getter didn't throw ANE when null key is passed");
            AssertException.Throws <ArgumentNullException>(
                () => dictionary[null] = 0);
            // "TestIDictionary:  FAILED.  this[] setter didn't throw ANE when null key is passed");

            AssertException.Throws <ArgumentException>(
                () => dictionary[1] = 0);
            // "TestIDictionary:  FAILED.  this[] setter didn't throw AE when invalid key type is passed");

            AssertException.Throws <ArgumentException>(
                () => dictionary["1"] = "0");
            // "TestIDictionary:  FAILED.  this[] setter didn't throw AE when invalid value type is passed");
        }
        public void PreArgProc_MissingArguments()
        {
            // 0. Setup
            TestLogger logger;

            // 1. Null logger
            AssertException.Expects <ArgumentNullException>(() => ArgumentProcessor.TryProcessArgs(null, null));

            using (EnvironmentVariableScope scope = new EnvironmentVariableScope())
            {
                CreateRunnerFilesInScope(scope);

                // 2. All required arguments missing
                logger = CheckProcessingFails(/* no command line args */);
                logger.AssertSingleErrorExists("/key:"); // we expect errors with info about the missing required parameters, which should include the primary alias
                logger.AssertSingleErrorExists("/name:");
                logger.AssertSingleErrorExists("/version:");
                logger.AssertErrorDoesNotExist("/runner:");
                logger.AssertErrorsLogged(3);

                // 3. Some required arguments missing
                logger = CheckProcessingFails("/k:key", "/v:version");

                logger.AssertErrorDoesNotExist("/key:");
                logger.AssertErrorDoesNotExist("/version:");
                logger.AssertErrorDoesNotExist("/runner:");

                logger.AssertSingleErrorExists("/name:");
                logger.AssertErrorsLogged(1);

                // 4. Argument is present but has no value
                logger = CheckProcessingFails("/key:k1", "/name:n1", "/version:");

                logger.AssertErrorDoesNotExist("/key:");
                logger.AssertErrorDoesNotExist("/name:");
                logger.AssertErrorDoesNotExist("/runner:");

                logger.AssertSingleErrorExists("/version:");
                logger.AssertErrorsLogged(1);
            }
        }
        public void BrokerInteractiveRequestTest()
        {
            string CanonicalizedAuthority = AuthorityInfo.CanonicalizeAuthorityUri(CoreHelpers.UrlDecode(MsalTestConstants.AuthorityTestTenant));

            using (var harness = CreateTestHarness())
            {
                // Arrange
                var parameters = harness.CreateAuthenticationRequestParameters(
                    MsalTestConstants.AuthorityTestTenant,
                    null,
                    null,
                    null,
                    MsalTestConstants.ExtraQueryParams);

                // Act
                BrokerFactory            brokerFactory            = new BrokerFactory();
                BrokerInteractiveRequest brokerInteractiveRequest = new BrokerInteractiveRequest(parameters, null, null, null, brokerFactory.Create(harness.ServiceBundle));
                Assert.AreEqual(false, brokerInteractiveRequest.Broker.CanInvokeBroker(null));
                AssertException.TaskThrowsAsync <PlatformNotSupportedException>(() => brokerInteractiveRequest.Broker.AcquireTokenUsingBrokerAsync(new Dictionary <string, string>())).ConfigureAwait(false);
            }
        }
示例#20
0
        public void Should_call_task_exception_only_on_failing_theories()
        {
            var exception1 = new AssertException("Broken1");
            var method     = testClass.AddMethod("TestMethod1", parameters =>
            {
                var value = (int)parameters[0];
                if (value == 12)
                {
                    throw exception1;
                }
            },
                                                 new[] { Parameter.Create <int>("value") }, new TheoryAttribute(),
                                                 new InlineDataAttribute(12), new InlineDataAttribute(33));

            Run();

            var theoryTasks = method.TheoryTasks;

            Messages.OfEquivalentTask(theoryTasks[0]).AssertTaskException(exception1);
            Messages.OfEquivalentTask(theoryTasks[1]).AssertTaskFinishedSuccessfully();
        }
        public void ClientIdMustBeAGuid()
        {
            var ex = AssertException.Throws <MsalClientException>(
                () => PublicClientApplicationBuilder.Create("http://my.app")
                .WithAuthority(TestConstants.AadAuthorityWithTestTenantId)
                .Build());

            Assert.AreEqual(MsalError.ClientIdMustBeAGuid, ex.ErrorCode);

            ex = AssertException.Throws <MsalClientException>(
                () => PublicClientApplicationBuilder.Create("http://my.app")
                .WithAuthority(TestConstants.B2CAuthority)
                .Build());

            Assert.AreEqual(MsalError.ClientIdMustBeAGuid, ex.ErrorCode);

            // ADFS does not have this constraint
            PublicClientApplicationBuilder.Create("http://my.app")
            .WithAuthority(new Uri(TestConstants.ADFSAuthority))
            .Build();
        }
示例#22
0
        public void Manifest_InvalidCharsInName_Throws()
        {
            // Arrange
            JarManifestBuilder builder = new JarManifestBuilder();

            string[] invalidNames =
            {
                "", // empty
                null,
                "%",
                "1234!",
                "a b",   // whitespace
                "1\r\n2" // more whitespace
            };

            // Act and assert
            foreach (string name in invalidNames)
            {
                AssertException.Expect <ArgumentException>(() => builder.SetProperty(name, "valid.property"));
            }
        }
        public void InnerExceptionIncludedWithAdalClaimsChallengeExceptionTestAsync()
        {
            var context    = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, new TokenCache());
            var credential = new ClientCredential(TestConstants.DefaultClientId, TestConstants.DefaultClientSecret);

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityCommonTenant))
            {
                Method          = HttpMethod.Post,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent(responseContent)
                }
            });

            var result = AssertException.TaskThrows <AdalClaimChallengeException>(() =>
                                                                                  context.AcquireTokenAsync(TestConstants.DefaultResource, credential));

            // Check inner exception
            Assert.AreEqual("Response status code does not indicate success: 400 (BadRequest).", result.InnerException.Message);
            Assert.AreEqual(responseContent + ": Unknown error", result.InnerException.InnerException.Message);
        }
示例#24
0
        private static async Task RunAfterAccessFailureAsync(
            IPublicClientApplication pca,
            Func <Task> operationThatTouchesCache)
        {
            bool beforeAccessCalled = false;
            bool afterAccessCalled  = false;

            pca.UserTokenCache.SetBeforeAccess(args =>
            {
                beforeAccessCalled = true;
                throw new InvalidOperationException();
            });

            pca.UserTokenCache.SetAfterAccess(args => { afterAccessCalled = true; });

            await AssertException.TaskThrowsAsync <InvalidOperationException>(
                operationThatTouchesCache).ConfigureAwait(false);

            Assert.IsTrue(beforeAccessCalled);
            Assert.IsTrue(afterAccessCalled);
        }
示例#25
0
        public void CapabilitiesFaultTest()
        {
            RunTest(() =>
            {
                MessageSpoiler spoiler = new MessageSpoiler();

                Dictionary <string, string> namespaces = new Dictionary <string, string>();
                namespaces.Add("s", "http://www.w3.org/2003/05/soap-envelope");
                namespaces.Add("onvif", "http://www.onvif.org/ver10/device/wsdl");

                Dictionary <string, string> replacements = new Dictionary <string, string>();
                replacements.Add("/s:Envelope/s:Body/onvif:GetCapabilities/onvif:Category", "XYZ");

                spoiler.Namespaces     = namespaces;
                spoiler.NodesToReplace = replacements;

                SetBreakingBehaviour(spoiler);

                bool fault = false;

                try
                {
                    GetCapabilities(new CapabilityCategory[] { CapabilityCategory.All });
                }
                catch (FaultException exception)
                {
                    fault = true;
                    SaveStepFault(exception);
                    StepPassed();
                }

                if (!fault)
                {
                    string reason      = "No SOAP fault returned from the DUT";
                    AssertException ex = new AssertException(reason);
                    StepFailed(ex);
                    throw ex;
                }
            });
        }
        public async Task AcquireTokenByIntegratedWindowsAuthTest_ManagedUser_DiscoveryFailed_ThrowsExceptionAsync()
        {
            // Arrange
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddInstanceDiscoveryMockHandler();

                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedMethod  = HttpMethod.Get,
                    ResponseMessage = new HttpResponseMessage(HttpStatusCode.NotFound)
                    {
                        Content = new StringContent(
                            "{\"ver\":\"1.0\"," +
                            "\"account_type\":\"Managed\"," +
                            "\"domain_name\":\"some_domain.onmicrosoft.com\"," +
                            "\"cloud_audience_urn\":\"urn:federation:MicrosoftOnline\"," +
                            "\"cloud_instance_name\":\"login.microsoftonline.com\"}")
                    }
                });

                PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                              .WithAuthority(new Uri(ClientApplicationBase.DefaultAuthority), true)
                                              .WithHttpManager(httpManager)
                                              .BuildConcrete();

                // Act
                MsalServiceException exception = await AssertException.TaskThrowsAsync <MsalServiceException>(
                    async() => await app
                    .AcquireTokenByIntegratedWindowsAuth(TestConstants.s_scope)
                    .WithUsername(TestConstants.s_user.Username)
                    .ExecuteAsync(CancellationToken.None)
                    .ConfigureAwait(false)).ConfigureAwait(false);

                // Assert
                Assert.AreEqual(MsalError.UserRealmDiscoveryFailed, exception.ErrorCode);
                Assert.AreEqual(HttpStatusCode.NotFound, (HttpStatusCode)exception.StatusCode);
            }
        }
        private async Task <PublicClientApplication> SetupAndAcquireOnceAsync(
            MockHttpAndServiceBundle httpManagerAndBundle,
            int httpStatusCode,
            int?retryAfterInSeconds,
            TokenResponseType tokenResponseType)
        {
            Trace.WriteLine("1. Setup test");
            var httpManager = httpManagerAndBundle.HttpManager;

            PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                          .WithHttpManager(httpManager)
                                          .BuildConcrete();

            new TokenCacheHelper().PopulateCache(app.UserTokenCacheInternal.Accessor, expiredAccessTokens: true);

            var tokenResponse = httpManager.AddAllMocks(tokenResponseType);

            UpdateStatusCodeAndHeaders(tokenResponse.ResponseMessage, httpStatusCode, retryAfterInSeconds);

            if (httpStatusCode >= 500 && httpStatusCode < 600 && !retryAfterInSeconds.HasValue)
            {
                var response2 = httpManager.AddTokenResponse(
                    tokenResponseType, s_throttlingHeader);
                UpdateStatusCodeAndHeaders(response2.ResponseMessage, httpStatusCode, retryAfterInSeconds);
            }

            var account = (await app.GetAccountsAsync().ConfigureAwait(false)).Single();

            Trace.WriteLine("2. First failing call ");
            var ex = await AssertException.TaskThrowsAsync <MsalServiceException>(
                () => app.AcquireTokenSilent(TestConstants.s_scope, account).ExecuteAsync(),
                allowDerived : true)
                     .ConfigureAwait(false);

            Assert.AreEqual(0, httpManager.QueueSize, "No more requests expected");
            Assert.AreEqual(httpStatusCode, ex.StatusCode);
            Assert.AreEqual(tokenResponseType == TokenResponseType.InvalidGrant, ex is MsalUiRequiredException);

            return(app);
        }
        public async Task FederatedUsernamePasswordCommonAuthorityTestAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddInstanceDiscoveryMockHandler();
                httpManager.AddMockHandlerForTenantEndpointDiscovery(TestConstants.AuthorityCommonTenant);
                AddMockHandlerDefaultUserRealmDiscovery(httpManager);
                AddMockHandlerMex(httpManager);
                AddMockHandlerWsTrustUserName(httpManager);

                // AAD
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedUrl     = "https://login.microsoftonline.com/common/oauth2/v2.0/token",
                    ExpectedMethod  = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateInvalidRequestTokenResponseMessage()
                });

                PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                              .WithAuthority(new Uri(ClientApplicationBase.DefaultAuthority), true)
                                              .WithHttpManager(httpManager)
                                              .WithTelemetry(new TraceTelemetryConfig())
                                              .BuildConcrete();

                // Call acquire token
                MsalServiceException result = await AssertException.TaskThrowsAsync <MsalServiceException>(
                    async() => await app.AcquireTokenByUsernamePassword(
                        TestConstants.s_scope,
                        TestConstants.s_user.Username,
                        _secureString).ExecuteAsync(CancellationToken.None).ConfigureAwait(false)).ConfigureAwait(false);

                // Check inner exception
                Assert.AreEqual(MsalError.InvalidRequest, result.ErrorCode);

                // There should be no cached entries.
                Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count());
            }
        }
        private async Task <(MockHttpMessageHandler MockHttpHandler, Guid Correlationid)> RunSilentFlowWithTokenErrorAsync(AcquireTokenSilentParameterBuilder request, string errorCode)
        {
            _app.UserTokenCacheInternal.Accessor.ClearAccessTokens();

            var correlationId = Guid.NewGuid();
            var tokenRequest  = _harness.HttpManager.AddFailureTokenEndpointResponse(
                errorCode,
                TestConstants.AuthorityUtidTenant,
                correlationId.ToString());

            var ex = await AssertException.TaskThrowsAsync <MsalServiceException>(
                () => request.WithCorrelationId(correlationId).ExecuteAsync(),
                allowDerived : true)
                     .ConfigureAwait(false);

            Assert.AreEqual(
                correlationId,
                Guid.Parse(ex.CorrelationId),
                "Test error - Exception correlation ID does not match WithCorrelationId value");

            return(tokenRequest, correlationId);
        }
示例#30
0
        public async Task FailingTest_SeleniumFailureAsync()
        {
            var pca = PublicClientApplicationBuilder
                      .Create("1d18b3b0-251b-4714-a02a-9956cec86c2d")
                      .WithRedirectUri(SeleniumWebUI.FindFreeLocalhostRedirectUri())
                      .Build();

            // This should fail after a few seconds
            var seleniumLogic = new SeleniumWebUI((driver) =>
            {
                Trace.WriteLine("Looking for an element that does not exist");
                driver.FindElement(By.Id("i_hope_this_element_does_not_exist"));
            }, TestContext);

            // The exception propagated to the test should be Selenium exception,
            // the test should not wait for the TCP listener to time out
            await AssertException.TaskThrowsAsync <NoSuchElementException>(() => pca
                                                                           .AcquireTokenInteractive(s_scopes)
                                                                           .WithCustomWebUi(seleniumLogic)
                                                                           .ExecuteAsync(CancellationToken.None))
            .ConfigureAwait(false);
        }
        public async Task AcquireTokenByIntegratedWindowsAuthTest_UnknownUserAsync()
        {
            // Arrange
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddInstanceDiscoveryMockHandler();
                httpManager.AddMockHandlerForTenantEndpointDiscovery(TestConstants.AuthorityCommonTenant);

                // user realm discovery - unknown user type
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedMethod  = HttpMethod.Get,
                    ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent(
                            "{\"ver\":\"1.0\"," +
                            "\"account_type\":\"Bogus\"}")
                    }
                });

                PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                              .WithAuthority(new Uri(ClientApplicationBase.DefaultAuthority), true)
                                              .WithHttpManager(httpManager)
                                              .WithTelemetry(new TraceTelemetryConfig())
                                              .BuildConcrete();

                // Act
                MsalClientException exception = await AssertException.TaskThrowsAsync <MsalClientException>(
                    async() => await app
                    .AcquireTokenByIntegratedWindowsAuth(TestConstants.s_scope)
                    .WithUsername(TestConstants.s_user.Username)
                    .ExecuteAsync(CancellationToken.None)
                    .ConfigureAwait(false)).ConfigureAwait(false);

                // Assert
                Assert.AreEqual(MsalError.UnknownUserType, exception.ErrorCode);
            }
        }
        public void Should_call_task_exception_only_on_failing_theories()
        {
            var exception1 = new AssertException("Broken1");
            var method = testClass.AddMethod("TestMethod1", parameters =>
                                                                {
                                                                    var value = (int) parameters[0];
                                                                    if (value == 12)
                                                                        throw exception1;
                                                                },
                                             new[] {Parameter.Create<int>("value")}, new TheoryAttribute(),
                                             new InlineDataAttribute(12), new InlineDataAttribute(33));

            Run();

            var theoryTasks = method.TheoryTasks;
            Messages.OfEquivalentTask(theoryTasks[0]).AssertTaskException(exception1);
            Messages.OfEquivalentTask(theoryTasks[1]).AssertTaskFinishedSuccessfully();
        }
示例#33
0
    public void UserMessageIsTheMessage()
    {
        AssertException ex = new AssertException("UserMessage");

        Assert.Equal(ex.UserMessage, ex.Message);
    }
示例#34
0
    public void PreservesUserMessage()
    {
        AssertException ex = new AssertException("UserMessage");

        Assert.Equal("UserMessage", ex.UserMessage);
    }