private void AddMockResponseforManagedAccounts(MockHttpManager httpManager)
 {
     // user realm discovery
     httpManager.AddMockHandler(
         new MockHttpMessageHandler
     {
         ExpectedMethod  = HttpMethod.Get,
         ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
         {
             Content = new StringContent(
                 "{\"ver\":\"1.0\",\"account_type\":\"Managed\",\"domain_name\":\"id.com\"}")
         },
         ExpectedQueryParams = new Dictionary <string, string>
         {
             { "api-version", "1.0" }
         }
     });
 }
 private void AddMockHandlerDefaultUserRealmDiscovery_ManagedUser(MockHttpManager httpManager)
 {
     // user realm discovery
     httpManager.AddMockHandler(
         new MockHttpMessageHandler
     {
         ExpectedMethod  = HttpMethod.Get,
         ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
         {
             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\"}")
         }
     });
 }
        private MockHttpMessageHandler AddMockHandlerAadSuccess(MockHttpManager httpManager, string authority)
        {
            var handler = new MockHttpMessageHandler
            {
                ExpectedUrl      = authority + "oauth2/v2.0/token",
                ExpectedMethod   = HttpMethod.Post,
                ExpectedPostData = new Dictionary <string, string>
                {
                    { "grant_type", "urn:ietf:params:oauth:grant-type:saml1_1-bearer" },
                    { "scope", "openid offline_access profile r1/scope1 r1/scope2" }
                },
                ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage()
            };

            httpManager.AddMockHandler(handler);

            return(handler);
        }
Exemple #4
0
 private void AddMockedResponse(HttpResponseMessage responseMessage)
 {
     _httpManager.AddMockHandler(
         new MockHttpMessageHandler
     {
         ExpectedMethod         = HttpMethod.Get,
         ExpectedUrl            = "http://169.254.169.254/metadata/instance/compute",
         ExpectedRequestHeaders = new Dictionary <string, string>
         {
             { "Metadata", "true" }
         },
         ExpectedQueryParams = new Dictionary <string, string>
         {
             { "api-version", "2020-06-01" }
         },
         ResponseMessage = responseMessage
     });
 }
Exemple #5
0
        public void AcquireTokenSilentServiceErrorTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                              .WithAuthority(new Uri(ClientApplicationBase.DefaultAuthority), true)
                                              .WithHttpManager(httpManager)
                                              .WithTelemetry(new TraceTelemetryConfig())
                                              .BuildConcrete();
                httpManager.AddInstanceDiscoveryMockHandler();
                httpManager.AddMockHandlerForTenantEndpointDiscovery(TestConstants.AuthorityUtidTenant);

                //populate cache
                var tokenCacheHelper = new TokenCacheHelper();
                tokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor);

                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedMethod  = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateInvalidGrantTokenResponseMessage()
                });
                try
                {
                    Task <AuthenticationResult> task = app
                                                       .AcquireTokenSilent(
                        TestConstants.s_cacheMissScope,
                        new Account(TestConstants.s_userIdentifier, TestConstants.DisplayableId, null))
                                                       .WithAuthority(app.Authority)
                                                       .WithForceRefresh(false)
                                                       .ExecuteAsync(CancellationToken.None);

                    AuthenticationResult result = task.Result;
                    Assert.Fail("MsalUiRequiredException was expected");
                }
                catch (AggregateException ex)
                {
                    Assert.IsNotNull(ex.InnerException);
                    Assert.IsTrue(ex.InnerException is MsalUiRequiredException);
                    var msalExc = (MsalUiRequiredException)ex.InnerException;
                    Assert.AreEqual(msalExc.ErrorCode, MsalError.InvalidGrantError);
                }
            }
        }
Exemple #6
0
        public async Task TokensAreInterchangable_Regional_To_NonRegional_Async()
        {
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddRegionDiscoveryMockHandler(TestConstants.Region);
                httpManager.AddMockHandler(CreateTokenResponseHttpHandler(true));

                IConfidentialClientApplication appWithRegion = CreateCca(
                    httpManager,
                    ConfidentialClientApplication.AttemptRegionDiscovery);
                InMemoryTokenCache memoryTokenCache = new InMemoryTokenCache();
                memoryTokenCache.Bind(appWithRegion.AppTokenCache);

                IConfidentialClientApplication appWithoutRegion = CreateCca(
                    httpManager,
                    null);
                memoryTokenCache.Bind(appWithoutRegion.AppTokenCache);

                AuthenticationResult result = await appWithRegion
                                              .AcquireTokenForClient(TestConstants.s_scope)
                                              .ExecuteAsync(CancellationToken.None)
                                              .ConfigureAwait(false);

                Assert.AreEqual(TestConstants.Region, result.ApiEvent.RegionUsed);
                Assert.AreEqual((int)RegionSource.Imds, result.ApiEvent.RegionSource);
                Assert.AreEqual(null, result.ApiEvent.UserProvidedRegion);
                Assert.AreEqual(false, result.ApiEvent.IsValidUserProvidedRegion);
                Assert.AreEqual(false, result.ApiEvent.FallbackToGlobal);

                // when switching to non-region, token is found in the cache
                result = await appWithoutRegion
                         .AcquireTokenForClient(TestConstants.s_scope)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

                Assert.AreEqual(null, result.ApiEvent.RegionUsed);
                Assert.AreEqual((int)RegionSource.None, result.ApiEvent.RegionSource);
                Assert.AreEqual(null, result.ApiEvent.UserProvidedRegion);
                Assert.AreEqual(null, result.ApiEvent.IsValidUserProvidedRegion);
                Assert.AreEqual(null, result.ApiEvent.FallbackToGlobal);

                Assert.IsTrue(result.AuthenticationResultMetadata.TokenSource == TokenSource.Cache);
            }
        }
        public async Task ManagedUsernameIncorrectPasswordAcquireTokenTestAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddInstanceDiscoveryMockHandler();
                AddMockResponseforManagedAccounts(httpManager);

                var str = new SecureString();
                str.AppendChar('y');
                str.MakeReadOnly();

                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedMethod         = HttpMethod.Post,
                    ResponseMessage        = MockHelpers.CreateInvalidGrantTokenResponseMessage(),
                    ExpectedPostDataObject = new Dictionary <string, object>
                    {
                        { "grant_type", "password" },
                        { "username", TestConstants.s_user.Username },
                        { "password", _secureString }
                    }
                });

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

                // Call acquire token
                MsalUiRequiredException result = await Assert.ThrowsExceptionAsync <MsalUiRequiredException>(
                    () => app.AcquireTokenByUsernamePassword(
                        TestConstants.s_scope,
                        TestConstants.s_user.Username,
                        str).ExecuteAsync(CancellationToken.None)).ConfigureAwait(false);

                // Check error code
                Assert.AreEqual(MsalError.InvalidGrantError, result.ErrorCode);

                // There should be no cached entries.
                Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count());
            }
        }
Exemple #8
0
        [WorkItem(695)] // Fix for https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/695
        public void AcquireTokenSilentForceRefreshTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                              .WithAuthority(new Uri(ClientApplicationBase.DefaultAuthority), true)
                                              .WithHttpManager(httpManager)
                                              .WithTelemetry(new TraceTelemetryConfig())
                                              .BuildConcrete();

                var tokenCacheHelper = new TokenCacheHelper();
                tokenCacheHelper.PopulateCacheWithOneAccessToken(app.UserTokenCacheInternal.Accessor);
                var cacheAccess = app.UserTokenCache.RecordAccess();

                httpManager.AddInstanceDiscoveryMockHandler();
                httpManager.AddMockHandlerForTenantEndpointDiscovery(TestConstants.AuthorityUtidTenant);

                httpManager.AddMockHandler(
                    new MockHttpMessageHandler()
                {
                    ExpectedMethod  = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(
                        TestConstants.UniqueId,
                        TestConstants.DisplayableId,
                        TestConstants.s_scope.ToArray())
                });

                Task <AuthenticationResult> task = app
                                                   .AcquireTokenSilent(
                    TestConstants.s_scope.ToArray(),
                    new Account(TestConstants.s_userIdentifier, TestConstants.DisplayableId, null))
                                                   .WithForceRefresh(true)
                                                   .ExecuteAsync(CancellationToken.None);

                AuthenticationResult result = task.Result;
                Assert.IsNotNull(result);
                Assert.AreEqual(TestConstants.DisplayableId, result.Account.Username);
                Assert.AreEqual(TestConstants.s_scope.ToArray().AsSingleString(), result.Scopes.AsSingleString());

                Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count());
                Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count());
                cacheAccess.AssertAccessCounts(1, 1);
            }
        }
        public async Task MexEndpointFailsToResolveTestAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddInstanceDiscoveryMockHandler();
                httpManager.AddMockHandlerForTenantEndpointDiscovery(TestConstants.AuthorityOrganizationsTenant);
                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("Parsing WS metadata exchange failed", 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());
            }
        }
Exemple #10
0
        public void B2CLoginAuthorityCreateAuthority()
        {
            using (var httpManager = new MockHttpManager())
            {
                var appConfig = new ApplicationConfiguration()
                {
                    HttpManager   = httpManager,
                    AuthorityInfo = AuthorityInfo.FromAuthorityUri(TestConstants.B2CLoginAuthority, false)
                };

                var serviceBundle = ServiceBundle.Create(appConfig);

                // add mock response for tenant endpoint discovery
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedMethod  = HttpMethod.Get,
                    ExpectedUrl     = "https://sometenantid.b2clogin.com/tfp/sometenantid/policy/v2.0/.well-known/openid-configuration",
                    ResponseMessage = MockHelpers.CreateSuccessResponseMessage(
                        File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("OpenidConfiguration-B2CLogin.json")))
                });

                Authority instance = Authority.CreateAuthority(
                    serviceBundle,
                    TestConstants.B2CLoginAuthority);
                Assert.IsNotNull(instance);
                Assert.AreEqual(instance.AuthorityInfo.AuthorityType, AuthorityType.B2C);
                var resolver  = new AuthorityEndpointResolutionManager(serviceBundle);
                var endpoints = resolver.ResolveEndpointsAsync(
                    instance.AuthorityInfo,
                    null,
                    new RequestContext(serviceBundle, Guid.NewGuid()))
                                .GetAwaiter().GetResult();

                Assert.AreEqual(
                    "https://sometenantid.b2clogin.com/6babcaad-604b-40ac-a9d7-9fd97c0b779f/policy/oauth2/v2.0/authorize",
                    endpoints.AuthorizationEndpoint);
                Assert.AreEqual(
                    "https://sometenantid.b2clogin.com/6babcaad-604b-40ac-a9d7-9fd97c0b779f/policy/oauth2/v2.0/token",
                    endpoints.TokenEndpoint);
                Assert.AreEqual("https://sometenantid.b2clogin.com/6babcaad-604b-40ac-a9d7-9fd97c0b779f/v2.0/", endpoints.SelfSignedJwtAudience);
            }
        }
        public async Task AcquireTokenByIntegratedWindowsAuthInvalidClientTestAsync()
        {
            IDictionary <string, string> extraQueryParamsAndClaims =
                TestConstants.s_extraQueryParams.ToDictionary(e => e.Key, e => e.Value);

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

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

                httpManager.AddMockHandlerForTenantEndpointDiscovery(TestConstants.AuthorityCommonTenant);
                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.s_extraQueryParams)
                                              .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());
            }
        }
        public void AcquireTokenSilentScopeAndUserOverloadTenantSpecificAuthorityTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                PublicClientApplication app = PublicClientApplicationBuilder.Create(MsalTestConstants.ClientId)
                                              .WithAuthority(new Uri(MsalTestConstants.AuthorityGuestTenant), true)
                                              .WithHttpManager(httpManager)
                                              .WithTelemetry(new TraceTelemetryConfig())
                                              .BuildConcrete();
                _tokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor);
                app.UserTokenCacheInternal.Accessor.DeleteAccessToken(
                    new MsalAccessTokenCacheKey(
                        MsalTestConstants.ProductionPrefNetworkEnvironment,
                        MsalTestConstants.Utid,
                        MsalTestConstants.UserIdentifier,
                        MsalTestConstants.ClientId,
                        MsalTestConstants.ScopeForAnotherResourceStr));

                httpManager.AddInstanceDiscoveryMockHandler();
                httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityGuestTenant);

                httpManager.AddMockHandler(
                    new MockHttpMessageHandler()
                {
                    ExpectedMethod  = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(
                        MsalTestConstants.UniqueId,
                        MsalTestConstants.DisplayableId,
                        MsalTestConstants.Scope.ToArray())
                });

                Task <AuthenticationResult> task = app
                                                   .AcquireTokenSilent(
                    MsalTestConstants.Scope.ToArray(),
                    new Account(MsalTestConstants.UserIdentifier, MsalTestConstants.DisplayableId, null))
                                                   .ExecuteAsync(CancellationToken.None);

                AuthenticationResult result = task.Result;
                Assert.IsNotNull(result);
                Assert.AreEqual(MsalTestConstants.DisplayableId, result.Account.Username);
                Assert.AreEqual(MsalTestConstants.Scope.AsSingleString(), result.Scopes.AsSingleString());
            }
        }
        private void AddMockResponseforManagedAccounts(MockHttpManager httpManager)
        {
            httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityOrganizationsTenant);

            // user realm discovery
            httpManager.AddMockHandler(
                new MockHttpMessageHandler
            {
                Method          = HttpMethod.Get,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(
                        "{\"ver\":\"1.0\",\"account_type\":\"Managed\",\"domain_name\":\"id.com\"}")
                },
                QueryParams = new Dictionary <string, string>
                {
                    { "api-version", "1.0" }
                }
            });
        }
        private MockHttpMessageHandler AddMockHandlerDefaultUserRealmDiscovery(MockHttpManager httpManager)
        {
            var handler = new MockHttpMessageHandler
            {
                ExpectedMethod  = HttpMethod.Get,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(
                        "{\"ver\":\"1.0\",\"account_type\":\"federated\",\"domain_name\":\"microsoft.com\"," +
                        "\"federation_protocol\":\"WSTrust\",\"federation_metadata_url\":" +
                        "\"https://msft.sts.microsoft.com/adfs/services/trust/mex\"," +
                        "\"federation_active_auth_url\":\"https://msft.sts.microsoft.com/adfs/services/trust/2005/usernamemixed\"" +
                        ",\"cloud_instance_name\":\"login.microsoftonline.com\"}")
                }
            };

            // user realm discovery
            httpManager.AddMockHandler(handler);
            return(handler);
        }
Exemple #15
0
        public void FailedValidationMissingFieldsInDrsResponseTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);

                //add mock failure response for on-premise DRS request
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    Method      = HttpMethod.Get,
                    Url         = "https://enterpriseregistration.fabrikam.com/enrollmentserver/contract",
                    QueryParams = new Dictionary <string, string>
                    {
                        { "api-version", "1.0" }
                    },
                    ResponseMessage =
                        MockHelpers.CreateSuccessResponseMessage(
                            ResourceHelper.GetTestResourceRelativePath(File.ReadAllText("drs-response-missing-field.json")))
                });

                Authority instance = Authority.CreateAuthority(serviceBundle, CoreTestConstants.OnPremiseAuthority, true);
                Assert.IsNotNull(instance);
                Assert.AreEqual(instance.AuthorityType, AuthorityType.Adfs);
                try
                {
                    Task.Run(
                        async() =>
                    {
                        await instance.ResolveEndpointsAsync(
                            CoreTestConstants.FabrikamDisplayableId,
                            new RequestContext(null, new MsalLogger(Guid.NewGuid(), null))).ConfigureAwait(false);
                    }).GetAwaiter().GetResult();
                    Assert.Fail("ResolveEndpointsAsync should have failed here");
                }
                catch (Exception exc)
                {
                    Assert.IsNotNull(exc);
                }
            }
        }
        public void FailedValidationMissingFieldsTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);

                //add mock response for instance validation
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    Method      = HttpMethod.Get,
                    Url         = "https://login.windows.net/common/discovery/instance",
                    QueryParams = new Dictionary <string, string>
                    {
                        { "api-version", "1.0" },
                        { "authorization_endpoint", "https://login.microsoft0nline.com/mytenant.com/oauth2/v2.0/authorize" },
                    },
                    ResponseMessage = MockHelpers.CreateSuccessResponseMessage("{}")
                });

                var       aadInstanceDiscovery = new AadInstanceDiscovery(httpManager, new TelemetryManager());
                Authority instance             = Authority.CreateAuthority(serviceBundle, "https://login.microsoft0nline.com/mytenant.com", true);
                Assert.IsNotNull(instance);
                Assert.AreEqual(instance.AuthorityType, AuthorityType.Aad);
                try
                {
                    Task.Run(
                        async() =>
                    {
                        await instance.ResolveEndpointsAsync(
                            null,
                            new RequestContext(null, new MsalLogger(Guid.NewGuid(), null))).ConfigureAwait(false);
                    }).GetAwaiter().GetResult();
                    Assert.Fail("validation should have failed here");
                }
                catch (Exception exc)
                {
                    Assert.IsNotNull(exc);
                }
            }
        }
        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);
            }
        }
        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 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());
            }
        }
Exemple #20
0
        public async Task GetAuthorizationRequestUrlB2CTestAsync()
        {
            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 for tenant endpoint discovery
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedMethod  = HttpMethod.Get,
                    ResponseMessage = MockHelpers.CreateSuccessResponseMessage(
                        File.ReadAllText(
                            ResourceHelper.GetTestResourceRelativePath(@"OpenidConfiguration-QueryParams-B2C.json")))
                });

                var uri = await app
                          .GetAuthorizationRequestUrl(MsalTestConstants.Scope)
                          .WithLoginHint(MsalTestConstants.DisplayableId)
                          .ExecuteAsync(CancellationToken.None)
                          .ConfigureAwait(false);

                Assert.IsNotNull(uri);
                Dictionary <string, string> qp = CoreHelpers.ParseKeyValueList(uri.Query.Substring(1), '&', true, null);
                Assert.IsNotNull(qp);

                Assert.AreEqual("my-policy", qp["p"]);
                ValidateCommonQueryParams(qp);
                Assert.AreEqual("offline_access openid profile r1/scope1 r1/scope2", qp["scope"]);
            }
        }
Exemple #21
0
        public void B2CMicrosoftOnlineCreateAuthority()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);

                // add mock response for tenant endpoint discovery
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    Method          = HttpMethod.Get,
                    Url             = "https://login.microsoftonline.com/tfp/mytenant.com/my-policy/v2.0/.well-known/openid-configuration",
                    ResponseMessage = MockHelpers.CreateSuccessResponseMessage(
                        File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("OpenidConfiguration-B2C.json")))
                });

                Authority instance = Authority.CreateAuthority(
                    serviceBundle,
                    "https://login.microsoftonline.com/tfp/mytenant.com/my-policy/", true);
                Assert.IsNotNull(instance);
                Assert.AreEqual(instance.AuthorityType, AuthorityType.B2C);
                Task.Run(
                    async() =>
                {
                    await instance.ResolveEndpointsAsync(
                        null,
                        new RequestContext(null, new MsalLogger(Guid.NewGuid(), null))).ConfigureAwait(false);
                }).GetAwaiter().GetResult();

                Assert.AreEqual(
                    "https://login.microsoftonline.com/6babcaad-604b-40ac-a9d7-9fd97c0b779f/my-policy/oauth2/v2.0/authorize",
                    instance.AuthorizationEndpoint);
                Assert.AreEqual(
                    "https://login.microsoftonline.com/6babcaad-604b-40ac-a9d7-9fd97c0b779f/my-policy/oauth2/v2.0/token",
                    instance.TokenEndpoint);
                Assert.AreEqual("https://sts.windows.net/6babcaad-604b-40ac-a9d7-9fd97c0b779f/", instance.SelfSignedJwtAudience);
            }
        }
        public void FailedTenantDiscoveryMissingEndpointsTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);

                //add mock response for tenant endpoint discovery
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    Method          = HttpMethod.Get,
                    Url             = "https://login.microsoftonline.in/mytenant.com/v2.0/.well-known/openid-configuration",
                    ResponseMessage =
                        MockHelpers.CreateSuccessResponseMessage(
                            File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("OpenidConfiguration-MissingFields.json")))
                });

                var       aadInstanceDiscovery = new AadInstanceDiscovery(httpManager, new TelemetryManager());
                Authority instance             = Authority.CreateAuthority(serviceBundle, "https://login.microsoftonline.in/mytenant.com", false);
                Assert.IsNotNull(instance);
                Assert.AreEqual(instance.AuthorityType, AuthorityType.Aad);
                try
                {
                    Task.Run(
                        async() =>
                    {
                        await instance.ResolveEndpointsAsync(
                            null,
                            new RequestContext(null, new MsalLogger(Guid.NewGuid(), null))).ConfigureAwait(false);
                    }).GetAwaiter().GetResult();
                    Assert.Fail("validation should have failed here");
                }
                catch (MsalClientException exc)
                {
                    Assert.AreEqual(CoreErrorCodes.TenantDiscoveryFailedError, exc.ErrorCode);
                }
            }
        }
Exemple #23
0
        public async Task JsonWebTokenWithX509PublicCertSendCertificateOnBehalfOfTestAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                SetupMocks(httpManager);

                var certificate = new X509Certificate2(
                    ResourceHelper.GetTestResourceRelativePath("valid_cert.pfx"),
                    MsalTestConstants.DefaultPassword);
                var clientAssertion  = new ClientAssertionCertificate(certificate);
                var clientCredential = new ClientCredential(clientAssertion);
                var app = new ConfidentialClientApplication(
                    serviceBundle,
                    MsalTestConstants.ClientId,
                    ClientApplicationBase.DefaultAuthority,
                    MsalTestConstants.RedirectUri,
                    clientCredential,
                    _cache,
                    _cache)
                {
                    ValidateAuthority = false
                };
                var userAssertion = new UserAssertion(MsalTestConstants.DefaultAccessToken);

                //Check for x5c claim
                httpManager.AddMockHandler(X5CMockHandler);
                AuthenticationResult result =
                    await(app as IConfidentialClientApplicationWithCertificate).AcquireTokenOnBehalfOfWithCertificateAsync(
                        MsalTestConstants.Scope,
                        userAssertion).ConfigureAwait(false);
                Assert.IsNotNull(result.AccessToken);

                result = await app.AcquireTokenOnBehalfOfAsync(MsalTestConstants.Scope, userAssertion).ConfigureAwait(false);

                Assert.IsNotNull(result.AccessToken);
            }
        }
        public async Task ManagedUsernameSecureStringPasswordAcquireTokenTestAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddInstanceDiscoveryMockHandler();
                AddMockResponseforManagedAccounts(httpManager);

                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedMethod         = HttpMethod.Post,
                    ResponseMessage        = MockHelpers.CreateSuccessTokenResponseMessage(),
                    ExpectedPostDataObject = new Dictionary <string, object>
                    {
                        { "grant_type", "password" },
                        { "username", TestConstants.s_user.Username },
                        { "password", _secureString }
                    }
                });

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

                AuthenticationResult result = await app.AcquireTokenByUsernamePassword(
                    TestConstants.s_scope,
                    TestConstants.s_user.Username,
                    _secureString).ExecuteAsync(CancellationToken.None).ConfigureAwait(false);

                Assert.IsNotNull(result);
                Assert.AreEqual("some-access-token", result.AccessToken);
                Assert.IsNotNull(result.Account);
                Assert.AreEqual(TestConstants.s_user.Username, result.Account.Username);
            }
        }
        public void AcquireTokenByIntegratedWindowsAuthTest_UnknownUser()
        {
            // Arrange
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                httpManager.AddInstanceDiscoveryMockHandler();
                httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityHomeTenant);

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

                var app =
                    new PublicClientApplication(serviceBundle, MsalTestConstants.ClientId,
                                                ClientApplicationBase.DefaultAuthority);

                // Act
                var exception = AssertException.TaskThrows <MsalClientException>(
                    async() => await app.AcquireTokenByIntegratedWindowsAuthAsync(
                        MsalTestConstants.Scope,
                        MsalTestConstants.User.Username)
                    .ConfigureAwait(false));

                // Assert
                Assert.AreEqual(MsalError.UnknownUserType, exception.ErrorCode);
            }
        }
        public async Task ManagedUsernameSecureStringPasswordAcquireTokenTestAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                httpManager.AddInstanceDiscoveryMockHandler();
                AddMockResponseforManagedAccounts(httpManager);

                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    Method          = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(),
                    PostDataObject  = new Dictionary <string, object>
                    {
                        { "grant_type", "password" },
                        { "username", MsalTestConstants.User.Username },
                        { "password", _secureString }
                    }
                });

                var app = new PublicClientApplication(
                    serviceBundle,
                    MsalTestConstants.ClientId,
                    ClientApplicationBase.DefaultAuthority);

                var result = await app.AcquireTokenByUsernamePasswordAsync(
                    MsalTestConstants.Scope,
                    MsalTestConstants.User.Username,
                    _secureString).ConfigureAwait(false);

                Assert.IsNotNull(result);
                Assert.AreEqual("some-access-token", result.AccessToken);
                Assert.IsNotNull(result.Account);
                Assert.AreEqual(MsalTestConstants.User.Username, result.Account.Username);
            }
        }
        public async Task TokensAreInterchangable_NonRegional_To_Regional_Async()
        {
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddInstanceDiscoveryMockHandler();
                httpManager.AddMockHandler(CreateTokenResponseHttpHandler(false));

                IConfidentialClientApplication appWithRegion = CreateCca(
                    httpManager,
                    ConfidentialClientApplication.AttemptRegionDiscovery);
                InMemoryTokenCache memoryTokenCache = new InMemoryTokenCache();
                memoryTokenCache.Bind(appWithRegion.AppTokenCache);

                IConfidentialClientApplication appWithoutRegion = CreateCca(
                    httpManager,
                    null);
                memoryTokenCache.Bind(appWithoutRegion.AppTokenCache);

                AuthenticationResult result = await appWithoutRegion
                                              .AcquireTokenForClient(TestConstants.s_scope)
                                              .ExecuteAsync(CancellationToken.None)
                                              .ConfigureAwait(false);

                Assert.IsTrue(result.AuthenticationResultMetadata.TokenSource == TokenSource.IdentityProvider);

                httpManager.AddRegionDiscoveryMockHandler("uscentral");

                // when switching to non-region, token is found in the cache
                result = await appWithRegion
                         .AcquireTokenForClient(TestConstants.s_scope)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

                Assert.IsTrue(result.AuthenticationResultMetadata.TokenSource == TokenSource.Cache);
            }
        }
Exemple #28
0
        public async Task UserRegion_DiscoveryHappensOnce_Async()
        {
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddRegionDiscoveryMockHandler(TestConstants.Region);
                httpManager.AddMockHandler(CreateTokenResponseHttpHandler(true));

                IConfidentialClientApplication app = CreateCca(
                    httpManager,
                    TestConstants.Region);

                AuthenticationResult result = await app
                                              .AcquireTokenForClient(TestConstants.s_scope)
                                              .ExecuteAsync()
                                              .ConfigureAwait(false);

                Assert.AreEqual(TestConstants.Region, result.ApiEvent.RegionUsed);
                Assert.AreEqual(RegionAutodetectionSource.Imds, result.ApiEvent.RegionAutodetectionSource);
                Assert.AreEqual(RegionOutcome.UserProvidedValid, result.ApiEvent.RegionOutcome);
                Assert.AreEqual(null, result.AuthenticationResultMetadata.RegionDetails.AutoDetectionError);
                Assert.AreEqual(TestConstants.Region, result.AuthenticationResultMetadata.RegionDetails.RegionUsed);
                Assert.AreEqual(RegionOutcome.UserProvidedValid, result.AuthenticationResultMetadata.RegionDetails.RegionOutcome);

                Assert.IsTrue(result.AuthenticationResultMetadata.TokenSource == TokenSource.IdentityProvider);

                result = await app
                         .AcquireTokenForClient(TestConstants.s_scope)
                         .ExecuteAsync()
                         .ConfigureAwait(false);

                Assert.IsTrue(result.AuthenticationResultMetadata.TokenSource == TokenSource.Cache);
                Assert.AreEqual(null, result.AuthenticationResultMetadata.RegionDetails.AutoDetectionError);
                Assert.AreEqual(TestConstants.Region, result.AuthenticationResultMetadata.RegionDetails.RegionUsed);
                Assert.AreEqual(RegionOutcome.UserProvidedValid, result.AuthenticationResultMetadata.RegionDetails.RegionOutcome);
            }
        }
        public async Task DstsClientCredentialSuccessfulTestAsync(string authority)
        {
            using (var httpManager = new MockHttpManager())
            {
                IConfidentialClientApplication app = ConfidentialClientApplicationBuilder
                                                     .Create(TestConstants.ClientId)
                                                     .WithHttpManager(httpManager)
                                                     .WithAuthority(authority)
                                                     .WithClientSecret(TestConstants.ClientSecret)
                                                     .Build();

                Assert.AreEqual(authority + "/", app.Authority);
                var confidentailClientApp = (ConfidentialClientApplication)app;
                Assert.AreEqual(AuthorityType.Dsts, confidentailClientApp.AuthorityInfo.AuthorityType);

                httpManager.AddMockHandler(CreateTokenResponseHttpHandler(authority));

                AuthenticationResult result = await app
                                              .AcquireTokenForClient(TestConstants.s_scope)
                                              .ExecuteAsync(CancellationToken.None)
                                              .ConfigureAwait(false);

                Assert.IsNotNull(result);
                Assert.IsNotNull(result.AccessToken);
                Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource);

                result = await app
                         .AcquireTokenForClient(TestConstants.s_scope)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

                Assert.IsNotNull(result);
                Assert.IsNotNull(result.AccessToken);
                Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource);
            }
        }
        // Test for https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/2514
        public async Task AuthorityValidationHappensOnNonRegionalAuthorityAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                var handler = new MockHttpMessageHandler()
                {
                    ExpectedUrl     = "https://login.microsoftonline.com/common/discovery/instance",
                    ExpectedMethod  = HttpMethod.Get,
                    ResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest)
                    {
                        Content = new StringContent(TestConstants.DiscoveryFailedResponse)
                    }
                };

                httpManager.AddMockHandler(handler);

                var app = ConfidentialClientApplicationBuilder
                          .Create(TestConstants.ClientId)
                          .WithAuthority("https://invalid.com/common")
                          .WithRedirectUri(TestConstants.RedirectUri)
                          .WithHttpManager(httpManager)
                          .WithClientSecret(TestConstants.ClientSecret)
                          .Build();

                // Act
                var ex = await AssertException.TaskThrowsAsync <MsalServiceException>(() => app
                                                                                      .AcquireTokenForClient(TestConstants.s_scope)
                                                                                      .ExecuteAsync())
                         .ConfigureAwait(false);

                // Assert
                Assert.AreEqual(MsalError.InvalidInstance, ex.ErrorCode);
                var qp = CoreHelpers.ParseKeyValueList(handler.ActualRequestMessage.RequestUri.Query.Substring(1), '&', true, null);
                Assert.AreEqual("https://invalid.com/common/oauth2/v2.0/authorize", qp["authorization_endpoint"]);
            }
        }