public async Task AcquireTokenByIntegratedWindowsAuthTestAsync()
        {
            var ui = new MockWebUI
            {
                MockResult = new AuthorizationResult(
                    AuthorizationStatus.Success,
                    MsalTestConstants.AuthorityHomeTenant + "?code=some-code")
            };

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

                httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityHomeTenant);
                AddMockHandlerDefaultUserRealmDiscovery(httpManager);
                AddMockHandlerMex(httpManager);
                AddMockHandlerWsTrustWindowsTransport(httpManager);
                AddMockHandlerAadSuccess(httpManager, MsalTestConstants.AuthorityHomeTenant);

                var app =
                    new PublicClientApplication(serviceBundle, MsalTestConstants.ClientId,
                                                ClientApplicationBase.DefaultAuthority);
                var result = await app
                             .AcquireTokenByIntegratedWindowsAuthAsync(MsalTestConstants.Scope, MsalTestConstants.User.Username)
                             .ConfigureAwait(false);

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

                httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityHomeTenant);
                AddMockHandlerDefaultUserRealmDiscovery_ManagedUser(httpManager);

                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.IntegratedWindowsAuthNotSupportedForManagedUser, exception.ErrorCode);
            }
        }
        public async Task WsTrustRequestFailureTestAsync()
        {
            string uri      = "https://some/address/usernamemixed";
            var    endpoint = new WsTrustEndpoint(new Uri(uri), WsTrustVersion.WsTrust13);

            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                httpManager.AddMockHandlerContentNotFound(HttpMethod.Post, url: uri);

                var requestContext = new RequestContext(null, new MsalLogger(Guid.NewGuid(), null));
                try
                {
                    var message = endpoint.BuildTokenRequestMessageWindowsIntegratedAuth("urn:federation:SomeAudience");

                    WsTrustResponse wstResponse =
                        await serviceBundle.WsTrustWebRequestManager.GetWsTrustResponseAsync(endpoint, message, requestContext).ConfigureAwait(false);

                    Assert.Fail("We expect an exception to be thrown here");
                }
                catch (MsalException ex)
                {
                    Assert.AreEqual(CoreErrorCodes.FederatedServiceReturnedError, ex.ErrorCode);
                }
            }
        }
Beispiel #4
0
        public void ValidationOffSuccessTest()
        {
            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://fs.contoso.com/adfs/.well-known/openid-configuration",
                    ResponseMessage =
                        MockHelpers.CreateSuccessResponseMessage(
                            ResourceHelper.GetTestResourceRelativePath(File.ReadAllText("OpenidConfiguration-OnPremise.json")))
                });

                Authority instance = Authority.CreateAuthority(serviceBundle, CoreTestConstants.OnPremiseAuthority, false);
                Assert.IsNotNull(instance);
                Assert.AreEqual(instance.AuthorityType, AuthorityType.Adfs);
                Task.Run(
                    async() =>
                {
                    await instance.ResolveEndpointsAsync(
                        CoreTestConstants.FabrikamDisplayableId,
                        new RequestContext(null, new MsalLogger(Guid.NewGuid(), null))).ConfigureAwait(false);
                }).GetAwaiter().GetResult();

                Assert.AreEqual("https://fs.contoso.com/adfs/oauth2/authorize/", instance.AuthorizationEndpoint);
                Assert.AreEqual("https://fs.contoso.com/adfs/oauth2/token/", instance.TokenEndpoint);
                Assert.AreEqual("https://fs.contoso.com/adfs", instance.SelfSignedJwtAudience);
            }
        }
        public async Task WsTrustRequestTestAsync()
        {
            string wsTrustAddress = "https://some/address/usernamemixed";
            var    endpoint       = new WsTrustEndpoint(new Uri(wsTrustAddress), WsTrustVersion.WsTrust13);

            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler()
                {
                    Url             = wsTrustAddress,
                    Method          = HttpMethod.Post,
                    ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent(
                            File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("WsTrustResponse13.xml")))
                    }
                });

                var requestContext  = new RequestContext(null, new MsalLogger(Guid.NewGuid(), null));
                var wsTrustRequest  = endpoint.BuildTokenRequestMessageWindowsIntegratedAuth("urn:federation:SomeAudience");
                var wsTrustResponse = await serviceBundle.WsTrustWebRequestManager.GetWsTrustResponseAsync(endpoint, wsTrustRequest, requestContext)
                                      .ConfigureAwait(false);

                Assert.IsNotNull(wsTrustResponse.Token);
            }
        }
        public void ManagedUsernameNoPasswordAcquireTokenTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                httpManager.AddInstanceDiscoveryMockHandler();
                AddMockResponseforManagedAccounts(httpManager);

                _cache.ClientId = MsalTestConstants.ClientId;
                var app = new PublicClientApplication(serviceBundle, MsalTestConstants.ClientId,
                                                      ClientApplicationBase.DefaultAuthority)
                {
                    UserTokenCache = _cache
                };

                SecureString str = null;

                // Call acquire token
                var result = AssertException.TaskThrows <MsalException>(
                    async() => await app.AcquireTokenByUsernamePasswordAsync(
                        MsalTestConstants.Scope,
                        MsalTestConstants.User.Username,
                        str).ConfigureAwait(false));

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

                // There should be no cached entries.
                Assert.AreEqual(0, _cache.TokenCacheAccessor.AccessTokenCount);
            }
        }
        public void TestDeviceCodeCancel()
        {
            using (var httpManager = new MockHttpManager())
            {
                var       serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                const int NumberOfAuthorizationPendingRequestsToInject = 0;
                var       parameters = CreateAuthenticationParametersAndSetupMocks(
                    httpManager,
                    NumberOfAuthorizationPendingRequestsToInject,
                    out HashSet <string> expectedScopes);

                _cache.ServiceBundle = serviceBundle;

                var cancellationSource = new CancellationTokenSource();

                DeviceCodeResult actualDeviceCodeResult = null;
                var request = new DeviceCodeRequest(
                    serviceBundle,
                    parameters,
                    ApiEvent.ApiIds.None,
                    async result =>
                {
                    await Task.Delay(200, CancellationToken.None).ConfigureAwait(false);
                    actualDeviceCodeResult = result;
                });

                // We setup the cancel before calling the RunAsync operation since we don't check the cancel
                // until later and the mock network calls run insanely fast for us to timeout for them.
                cancellationSource.Cancel();
                AssertException.TaskThrows <OperationCanceledException>(() => request.RunAsync(cancellationSource.Token));
            }
        }
        public void ExpiredTokenRefreshFlowTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                var        serviceBundle        = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                var        aadInstanceDiscovery = new AadInstanceDiscovery(httpManager, new TelemetryManager());
                Authority  authority            = Authority.CreateAuthority(serviceBundle, MsalTestConstants.AuthorityHomeTenant, false);
                TokenCache cache = new TokenCache()
                {
                    ClientId      = MsalTestConstants.ClientId,
                    ServiceBundle = serviceBundle
                };
                _tokenCacheHelper.PopulateCache(cache.TokenCacheAccessor);

                AuthenticationRequestParameters parameters = new AuthenticationRequestParameters()
                {
                    Authority      = authority,
                    ClientId       = MsalTestConstants.ClientId,
                    Scope          = MsalTestConstants.Scope,
                    TokenCache     = cache,
                    RequestContext = new RequestContext(null, new MsalLogger(Guid.Empty, null)),
                    Account        = new Account(MsalTestConstants.UserIdentifier, MsalTestConstants.DisplayableId, null)
                };

                // set access tokens as expired
                foreach (var atCacheItemStr in cache.GetAllAccessTokenCacheItems(new RequestContext(null, new MsalLogger(Guid.NewGuid(), null))))
                {
                    MsalAccessTokenCacheItem accessItem =
                        JsonHelper.DeserializeFromJson <MsalAccessTokenCacheItem>(atCacheItemStr);
                    accessItem.ExpiresOnUnixTimestamp =
                        ((long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds).ToString(CultureInfo.InvariantCulture);

                    cache.AddAccessTokenCacheItem(accessItem);
                }
                TestCommon.MockInstanceDiscoveryAndOpenIdRequest(httpManager);

                httpManager.AddMockHandler(new MockHttpMessageHandler()
                {
                    Method          = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage()
                });

                var crypto = PlatformProxyFactory.GetPlatformProxy().CryptographyManager;

                SilentRequest request = new SilentRequest(
                    serviceBundle,
                    parameters,
                    ApiEvent.ApiIds.None,
                    false);

                Task <AuthenticationResult> task   = request.RunAsync(CancellationToken.None);
                AuthenticationResult        result = task.Result;
                Assert.IsNotNull(result);
                Assert.AreEqual("some-access-token", result.AccessToken);
                Assert.AreEqual(MsalTestConstants.Scope.AsSingleString(), result.Scopes.AsSingleString());
            }
        }
Beispiel #9
0
 private static async Task RunWithMockHttpAsync(Func <MockHttpManager, IServiceBundle, MyReceiver, Task> action)
 {
     using (var httpManager = new MockHttpManager())
     {
         var receiver      = new MyReceiver();
         var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager, receiver);
         await action(httpManager, serviceBundle, receiver).ConfigureAwait(false);
     }
 }
Beispiel #10
0
 private static void RunWithMockHttp(Action <MockHttpManager, IServiceBundle, MyReceiver> action)
 {
     using (var httpManager = new MockHttpManager())
     {
         var receiver      = new MyReceiver();
         var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager, receiver);
         action(httpManager, serviceBundle, receiver);
     }
 }
Beispiel #11
0
        public void FailedValidationResourceNotInTrustedRealmTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);

                //add mock 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.json")))
                });


                //add mock response for on-premise webfinger request
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    Method      = HttpMethod.Get,
                    Url         = "https://fs.fabrikam.com/adfs/.well-known/webfinger",
                    QueryParams = new Dictionary <string, string>
                    {
                        { "resource", "https://fs.contoso.com" },
                        { "rel", "http://schemas.microsoft.com/rel/trusted-realm" }
                    },
                    ResponseMessage = MockHelpers.CreateSuccessWebFingerResponseMessage("https://fs.some-other-sts.com")
                });

                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);
                }
            }
        }
Beispiel #12
0
        public void GetExactScopesMatchedAccessTokenTest()
        {
            var atItem = Credential.CreateAccessToken(
                MsalTestConstants.HomeAccountId,
                MsalTestConstants.ProductionPrefNetworkEnvironment,
                new Uri(MsalTestConstants.AuthorityTestTenant).GetRealm(),
                MsalTestConstants.ClientId,
                ScopeUtils.JoinScopes(MsalTestConstants.Scope),
                TimeUtils.GetSecondsFromEpochNow(),
                TimeUtils.GetSecondsFromEpochNow() + MsalCacheV2TestConstants.ValidExpiresIn,
                TimeUtils.GetSecondsFromEpochNow() + MsalCacheV2TestConstants.ValidExtendedExpiresIn,
                TheSecret,
                string.Empty);

            _storageWorker.WriteCredentials(
                new List <Credential>
            {
                atItem
            });

            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);

                var cacheManager = new CacheManager(
                    _storageManager,
                    new AuthenticationRequestParameters
                {
                    Account = MsalTestConstants.User,

                    // TODO:  In MSALC++, the request parameters only really needs the
                    // Authority URI itself since the cache isn't meant to
                    // do ANY network calls.
                    // So it would be great if we could reduce the complexity/dependencies
                    // here and do any of the validated authority cache / instance discovery
                    // outside of the context of the authentication parameters and
                    // cache interaction and just track the authority we're using...

                    // AccountId = MsalTestConstants.HomeAccountId,
                    // Authority = new Uri(MsalTestConstants.AuthorityTestTenant),
                    Authority = Authority.CreateAuthority(
                        serviceBundle,
                        MsalTestConstants.AuthorityTestTenant,
                        false),
                    ClientId = MsalTestConstants.ClientId,
                    Scope    = new SortedSet <string>(MsalCacheV2TestConstants.Scope) // todo(mzuber):  WHY SORTED SET?
                });

                Assert.IsTrue(cacheManager.TryReadCache(out var tokenResponse, out var accountResponse));
                Assert.IsNotNull(tokenResponse);
                Assert.IsNull(accountResponse);

                Assert.AreEqual(TheSecret, tokenResponse.AccessToken);
            }
        }
        public void SuccessfulValidationTest()
        {
            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.microsoftonline.com/common/discovery/instance",
                    QueryParams = new Dictionary <string, string>
                    {
                        { "api-version", "1.1" },
                        {
                            "authorization_endpoint",
                            "https%3A%2F%2Flogin.microsoftonline.in%2Fmytenant.com%2Foauth2%2Fv2.0%2Fauthorize"
                        },
                    },
                    ResponseMessage = MockHelpers.CreateSuccessResponseMessage(
                        "{\"tenant_discovery_endpoint\":\"https://login.microsoftonline.in/mytenant.com/.well-known/openid-configuration\"}")
                });

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

                Authority instance = Authority.CreateAuthority(serviceBundle, "https://login.microsoftonline.in/mytenant.com", true);
                Assert.IsNotNull(instance);
                Assert.AreEqual(instance.AuthorityType, AuthorityType.Aad);
                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/oauth2/v2.0/authorize",
                    instance.AuthorizationEndpoint);
                Assert.AreEqual(
                    "https://login.microsoftonline.com/6babcaad-604b-40ac-a9d7-9fd97c0b779f/oauth2/v2.0/token",
                    instance.TokenEndpoint);
                Assert.AreEqual("https://sts.windows.net/6babcaad-604b-40ac-a9d7-9fd97c0b779f/", instance.SelfSignedJwtAudience);
                Assert.AreEqual("https://login.microsoftonline.in/common/userrealm/", instance.UserRealmUriPrefix);
            }
        }
        public void OAuthClient_FailsWithServiceExceptionWhenResponseIsHttpNotFound()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager, _myReceiver);

                var authority = Authority.CreateAuthority(serviceBundle, MsalTestConstants.AuthorityHomeTenant, false);

                var responseMessage = MockHelpers.CreateHttpStatusNotFoundResponseMessage();

                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    Method          = HttpMethod.Get,
                    ResponseMessage = responseMessage
                });

                var parameters = new AuthenticationRequestParameters
                {
                    Authority      = authority,
                    ClientId       = MsalTestConstants.ClientId,
                    Scope          = MsalTestConstants.Scope,
                    TokenCache     = null,
                    RequestContext = new RequestContext(null, new MsalLogger(Guid.NewGuid(), null)),
                    RedirectUri    = new Uri("some://uri"),
                };

                var ui = new MockWebUI();

                var request = new InteractiveRequest(
                    serviceBundle,
                    parameters,
                    ApiEvent.ApiIds.None,
                    MsalTestConstants.ScopeForAnotherResource.ToArray(),
                    MsalTestConstants.DisplayableId,
                    UIBehavior.SelectAccount,
                    ui);

                try
                {
                    request.ExecuteAsync(CancellationToken.None).Wait();

                    Assert.Fail("MsalException should have been thrown here");
                }
                catch (Exception exc)
                {
                    var serverEx = exc.InnerException as MsalServiceException;
                    Assert.IsNotNull(serverEx);
                    Assert.AreEqual((int)HttpStatusCode.NotFound, serverEx.StatusCode);
                    Assert.IsNotNull(serverEx.ResponseBody);
                    Assert.AreEqual(MsalError.HttpStatusNotFound, serverEx.ErrorCode);
                }
            }
        }
        public void TestDeviceCodeAuthSuccess()
        {
            const int NumberOfAuthorizationPendingRequestsToInject = 1;

            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);

                var parameters = CreateAuthenticationParametersAndSetupMocks(
                    httpManager,
                    NumberOfAuthorizationPendingRequestsToInject,
                    out HashSet <string> expectedScopes);

                _cache.ServiceBundle = serviceBundle;

                // Check that cache is empty
                Assert.AreEqual(0, _cache.TokenCacheAccessor.AccessTokenCount);
                Assert.AreEqual(0, _cache.TokenCacheAccessor.AccountCount);
                Assert.AreEqual(0, _cache.TokenCacheAccessor.IdTokenCount);
                Assert.AreEqual(0, _cache.TokenCacheAccessor.RefreshTokenCount);

                DeviceCodeResult actualDeviceCodeResult = null;
                var request = new DeviceCodeRequest(
                    serviceBundle,
                    parameters,
                    ApiEvent.ApiIds.None,
                    result =>
                {
                    actualDeviceCodeResult = result;
                    return(Task.FromResult(0));
                });
                Task <AuthenticationResult> task = request.RunAsync(CancellationToken.None);
                task.Wait();
                var authenticationResult = task.Result;
                Assert.IsNotNull(authenticationResult);
                Assert.IsNotNull(actualDeviceCodeResult);

                Assert.AreEqual(MsalTestConstants.ClientId, actualDeviceCodeResult.ClientId);
                Assert.AreEqual(ExpectedDeviceCode, actualDeviceCodeResult.DeviceCode);
                Assert.AreEqual(ExpectedInterval, actualDeviceCodeResult.Interval);
                Assert.AreEqual(ExpectedMessage, actualDeviceCodeResult.Message);
                Assert.AreEqual(ExpectedUserCode, actualDeviceCodeResult.UserCode);
                Assert.AreEqual(ExpectedVerificationUrl, actualDeviceCodeResult.VerificationUrl);

                CoreAssert.AreScopesEqual(expectedScopes.AsSingleString(), actualDeviceCodeResult.Scopes.AsSingleString());

                // Validate that entries were added to cache
                Assert.AreEqual(1, _cache.TokenCacheAccessor.AccessTokenCount);
                Assert.AreEqual(1, _cache.TokenCacheAccessor.AccountCount);
                Assert.AreEqual(1, _cache.TokenCacheAccessor.IdTokenCount);
                Assert.AreEqual(1, _cache.TokenCacheAccessor.RefreshTokenCount);
            }
        }
        public void MexEndpointFailsToResolveTest()
        {
            var ui = new MockWebUI
            {
                MockResult = new AuthorizationResult(
                    AuthorizationStatus.Success,
                    MsalTestConstants.AuthorityOrganizationsTenant + "?code=some-code")
            };

            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                httpManager.AddInstanceDiscoveryMockHandler();
                httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityOrganizationsTenant);
                AddMockHandlerDefaultUserRealmDiscovery(httpManager);

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

                _cache.ClientId = MsalTestConstants.ClientId;
                var app = new PublicClientApplication(serviceBundle, MsalTestConstants.ClientId,
                                                      ClientApplicationBase.DefaultAuthority)
                {
                    UserTokenCache = _cache
                };

                // Call acquire token, Mex parser fails
                var result = AssertException.TaskThrows <MsalException>(
                    async() => await app.AcquireTokenByUsernamePasswordAsync(
                        MsalTestConstants.Scope,
                        MsalTestConstants.User.Username,
                        _secureString).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, _cache.TokenCacheAccessor.AccessTokenCount);
            }
        }
        public void ManagedUsernamePasswordCommonAuthorityTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                httpManager.AddInstanceDiscoveryMockHandler();
                httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityCommonTenant);

                // 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" }
                    }
                });

                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    Method          = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateInvalidRequestTokenResponseMessage()
                });

                _cache.ClientId = MsalTestConstants.ClientId;
                var app = new PublicClientApplication(serviceBundle, MsalTestConstants.ClientId,
                                                      ClientApplicationBase.DefaultAuthority)
                {
                    UserTokenCache = _cache
                };

                // Call acquire token
                var result = AssertException.TaskThrows <MsalException>(
                    async() => await app.AcquireTokenByUsernamePasswordAsync(
                        MsalTestConstants.Scope,
                        MsalTestConstants.User.Username,
                        _secureString).ConfigureAwait(false));

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

                // There should be no cached entries.
                Assert.AreEqual(0, _cache.TokenCacheAccessor.AccessTokenCount);
            }
        }
        public void FailedValidationTest()
        {
            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.microsoftonline.com/common/discovery/instance",
                    QueryParams = new Dictionary <string, string>
                    {
                        { "api-version", "1.1" },
                        {
                            "authorization_endpoint",
                            "https%3A%2F%2Flogin.microsoft0nline.com%2Fmytenant.com%2Foauth2%2Fv2.0%2Fauthorize"
                        },
                    },
                    ResponseMessage = MockHelpers.CreateFailureMessage(
                        HttpStatusCode.BadRequest,
                        "{\"error\":\"invalid_instance\"," + "\"error_description\":\"AADSTS50049: " +
                        "Unknown or invalid instance. Trace " + "ID: b9d0894d-a9a4-4dba-b38e-8fb6a009bc00 " +
                        "Correlation ID: 34f7b4cf-4fa2-4f35-a59b" + "-54b6f91a9c94 Timestamp: 2016-08-23 " +
                        "20:45:49Z\",\"error_codes\":[50049]," + "\"timestamp\":\"2016-08-23 20:45:49Z\"," +
                        "\"trace_id\":\"b9d0894d-a9a4-4dba-b38e-8f" + "b6a009bc00\",\"correlation_id\":\"34f7b4cf-" +
                        "4fa2-4f35-a59b-54b6f91a9c94\"}")
                });

                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.IsTrue(exc is MsalServiceException);
                    Assert.AreEqual(((MsalServiceException)exc).ErrorCode, "invalid_instance");
                }
            }
        }
        public void SilentRefreshFailedNoCacheItemFoundTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle        = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                var aadInstanceDiscovery = new AadInstanceDiscovery(httpManager, new TelemetryManager());
                var authority            = Authority.CreateAuthority(serviceBundle, MsalTestConstants.AuthorityHomeTenant, false);
                _cache = new TokenCache()
                {
                    ClientId      = MsalTestConstants.ClientId,
                    ServiceBundle = serviceBundle
                };

                httpManager.AddInstanceDiscoveryMockHandler();

                var parameters = new AuthenticationRequestParameters()
                {
                    Authority = authority,
                    ClientId  = MsalTestConstants.ClientId,
                    Scope     = ScopeHelper.CreateSortedSetFromEnumerable(
                        new[]
                    {
                        "some-scope1",
                        "some-scope2"
                    }),
                    TokenCache     = _cache,
                    Account        = new Account(MsalTestConstants.UserIdentifier, MsalTestConstants.DisplayableId, null),
                    RequestContext = new RequestContext(null, new MsalLogger(Guid.NewGuid(), null))
                };

                var crypto           = PlatformProxyFactory.GetPlatformProxy().CryptographyManager;
                var telemetryManager = new TelemetryManager();

                try
                {
                    var request = new SilentRequest(serviceBundle, parameters, ApiEvent.ApiIds.None, false);
                    Task <AuthenticationResult> task = request.RunAsync(CancellationToken.None);
                    var authenticationResult         = task.Result;
                    Assert.Fail("MsalUiRequiredException should be thrown here");
                }
                catch (AggregateException ae)
                {
                    var exc = ae.InnerException as MsalUiRequiredException;
                    Assert.IsNotNull(exc, "Actual exception type is " + ae.InnerException.GetType());
                    Assert.AreEqual(MsalUiRequiredException.NoTokensFoundError, exc.ErrorCode);
                }
            }
        }
        public void FederatedUsernamePasswordCommonAuthorityTest()
        {
            var ui = new MockWebUI
            {
                MockResult = new AuthorizationResult(
                    AuthorizationStatus.Success,
                    MsalTestConstants.AuthorityCommonTenant + "?code=some-code")
            };

            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                httpManager.AddInstanceDiscoveryMockHandler();
                httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityCommonTenant);
                AddMockHandlerDefaultUserRealmDiscovery(httpManager);
                AddMockHandlerMex(httpManager);
                AddMockHandlerWsTrustUserName(httpManager);

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

                _cache.ClientId = MsalTestConstants.ClientId;
                var app = new PublicClientApplication(serviceBundle, MsalTestConstants.ClientId,
                                                      ClientApplicationBase.DefaultAuthority)
                {
                    UserTokenCache = _cache
                };

                // Call acquire token
                var result = AssertException.TaskThrows <MsalException>(
                    async() => await app.AcquireTokenByUsernamePasswordAsync(
                        MsalTestConstants.Scope,
                        MsalTestConstants.User.Username,
                        _secureString).ConfigureAwait(false));

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

                // There should be no cached entries.
                Assert.AreEqual(0, _cache.TokenCacheAccessor.AccessTokenCount);
            }
        }
        public void ManagedUsernameIncorrectPasswordAcquireTokenTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                httpManager.AddInstanceDiscoveryMockHandler();
                AddMockResponseforManagedAccounts(httpManager);

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

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

                _cache.ClientId = MsalTestConstants.ClientId;
                var app = new PublicClientApplication(serviceBundle, MsalTestConstants.ClientId,
                                                      ClientApplicationBase.DefaultAuthority)
                {
                    UserTokenCache = _cache
                };

                // Call acquire token
                var result = AssertException.TaskThrows <MsalException>(
                    async() => await app.AcquireTokenByUsernamePasswordAsync(
                        MsalTestConstants.Scope,
                        MsalTestConstants.User.Username,
                        str).ConfigureAwait(false));

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

                // There should be no cached entries.
                Assert.AreEqual(0, _cache.TokenCacheAccessor.AccessTokenCount);
            }
        }
        public void FederatedUsernameNullPasswordTest()
        {
            var ui = new MockWebUI
            {
                MockResult = new AuthorizationResult(
                    AuthorizationStatus.Success,
                    MsalTestConstants.AuthorityOrganizationsTenant + "?code=some-code")
            };

            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                httpManager.AddInstanceDiscoveryMockHandler();
                httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityOrganizationsTenant);
                AddMockHandlerDefaultUserRealmDiscovery(httpManager);
                AddMockHandlerMex(httpManager);

                // Mex does not return integrated auth endpoint (.../13/windowstransport)
                httpManager.AddMockHandlerContentNotFound(HttpMethod.Post,
                                                          "https://msft.sts.microsoft.com/adfs/services/trust/13/windowstransport");

                _cache.ClientId = MsalTestConstants.ClientId;
                var app = new PublicClientApplication(serviceBundle, MsalTestConstants.ClientId,
                                                      ClientApplicationBase.DefaultAuthority)
                {
                    UserTokenCache = _cache
                };

                SecureString str = null;

                // Call acquire token
                var result = AssertException.TaskThrows <MsalException>(
                    async() => await app.AcquireTokenByUsernamePasswordAsync(
                        MsalTestConstants.Scope,
                        MsalTestConstants.User.Username,
                        str).ConfigureAwait(false));

                // Check inner exception
                Assert.AreEqual(CoreErrorCodes.ParsingWsTrustResponseFailed, result.ErrorCode);

                // There should be no cached entries.
                Assert.AreEqual(0, _cache.TokenCacheAccessor.AccessTokenCount);
            }
        }
        public void MexParsingFailsTest()
        {
            var ui = new MockWebUI
            {
                MockResult = new AuthorizationResult(
                    AuthorizationStatus.Success,
                    MsalTestConstants.AuthorityOrganizationsTenant + "?code=some-code")
            };

            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                httpManager.AddInstanceDiscoveryMockHandler();
                httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityOrganizationsTenant);
                AddMockHandlerDefaultUserRealmDiscovery(httpManager);

                // MEX
                httpManager.AddMockHandlerContentNotFound(HttpMethod.Get,
                                                          "https://msft.sts.microsoft.com/adfs/services/trust/mex");

                _cache.ClientId = MsalTestConstants.ClientId;

                var app = new PublicClientApplication(serviceBundle, MsalTestConstants.ClientId,
                                                      ClientApplicationBase.DefaultAuthority)
                {
                    UserTokenCache = _cache
                };

                // Call acquire token
                var result = AssertException.TaskThrows <MsalException>(
                    async() => await app.AcquireTokenByUsernamePasswordAsync(
                        MsalTestConstants.Scope,
                        MsalTestConstants.User.Username,
                        _secureString).ConfigureAwait(false));

                // Check inner exception
                Assert.AreEqual("Response status code does not indicate success: 404 (NotFound).", result.Message);

                // There should be no cached entries.
                Assert.AreEqual(0, _cache.TokenCacheAccessor.AccessTokenCount);
            }
        }
        public void DuplicateQueryParameterErrorTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager, _myReceiver);
                var authority     = Authority.CreateAuthority(serviceBundle, MsalTestConstants.AuthorityHomeTenant, false);
                var parameters    = new AuthenticationRequestParameters
                {
                    Authority            = authority,
                    ClientId             = MsalTestConstants.ClientId,
                    Scope                = MsalTestConstants.Scope,
                    TokenCache           = null,
                    RequestContext       = new RequestContext(null, new MsalLogger(Guid.NewGuid(), null)),
                    RedirectUri          = new Uri("some://uri"),
                    ExtraQueryParameters = "extra=qp&prompt=login"
                };

                MockInstanceDiscoveryAndOpenIdRequest(httpManager);

                var request = new InteractiveRequest(
                    serviceBundle,
                    parameters,
                    ApiEvent.ApiIds.None,
                    MsalTestConstants.ScopeForAnotherResource.ToArray(),
                    null,
                    UIBehavior.ForceLogin,
                    new MockWebUI());

                try
                {
                    request.ExecuteAsync(CancellationToken.None).Wait();
                    Assert.Fail("MsalException should be thrown here");
                }
                catch (Exception exc)
                {
                    Assert.IsTrue(exc.InnerException is MsalException);
                    Assert.AreEqual(
                        MsalClientException.DuplicateQueryParameterError,
                        ((MsalException)exc.InnerException).ErrorCode);
                }
            }
        }
        public async Task MexEndpointFailsToResolveTestAsync()
        {
            // TODO: should we move this into a separate test class for WsTrustWebRequestManager?
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                httpManager.AddMockHandlerContentNotFound(HttpMethod.Get);

                try
                {
                    await serviceBundle.WsTrustWebRequestManager.GetMexDocumentAsync("http://somehost", _requestContext).ConfigureAwait(false);

                    Assert.Fail("We expect an exception to be thrown here");
                }
                catch (MsalException ex)
                {
                    Assert.AreEqual(CoreErrorCodes.AccessingWsMetadataExchangeFailed, ex.ErrorCode);
                }
            }
        }
        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);
                }
            }
        }
Beispiel #27
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);
            }
        }
Beispiel #28
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 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);
                }
            }
        }
        public async Task FederatedUsernamePasswordWithSecureStringAcquireTokenTestAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                httpManager.AddInstanceDiscoveryMockHandler();
                AddMockResponseForFederatedAccounts(httpManager);

                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);
            }
        }