Beispiel #1
0
        public void AcquireTokenAddTwoUsersTest()
        {
            PublicClientApplication app = new PublicClientApplication(TestConstants.ClientId);

            MockWebUI ui = new MockWebUI()
            {
                MockResult = new AuthorizationResult(AuthorizationStatus.Success,
                                                     TestConstants.AuthorityHomeTenant + "?code=some-code")
            };

            MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success,
                                                                   app.RedirectUri + "?code=some-code"));

            //add mock response for tenant endpoint discovery
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Get,
                ResponseMessage = MockHelpers.CreateOpenIdConfigurationResponse(TestConstants.AuthorityHomeTenant)
            });

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

            AuthenticationResult result = app.AcquireTokenAsync(TestConstants.Scope).Result;

            Assert.IsNotNull(result);
            Assert.IsNotNull(result.User);
            Assert.AreEqual(TestConstants.UniqueId, result.UniqueId);
            Assert.AreEqual(TestConstants.CreateUserIdentifer(), result.User.Identifier);
            Assert.AreEqual(TestConstants.DisplayableId, result.User.DisplayableId);
            Assert.AreEqual(TestConstants.IdentityProvider, result.TenantId);

            // repeat interactive call and pass in the same user
            MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success,
                                                                   app.RedirectUri + "?code=some-code"));

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(TestConstants.Scope.ToString(),
                                                                                MockHelpers.CreateIdToken(TestConstants.UniqueId + "more", TestConstants.DisplayableId + "more",
                                                                                                          TestConstants.IdentityProvider + "more"),
                                                                                MockHelpers.CreateClientInfo(TestConstants.Uid + "more",
                                                                                                             TestConstants.IdentityProvider + "more"))
            });

            result = app.AcquireTokenAsync(TestConstants.Scope).Result;
            Assert.IsNotNull(result);
            Assert.IsNotNull(result.User);
            Assert.AreEqual(TestConstants.UniqueId + "more", result.UniqueId);
            Assert.AreEqual(TestConstants.CreateUserIdentifer(TestConstants.Uid + "more",
                                                              TestConstants.IdentityProvider + "more"), result.User.Identifier);
            Assert.AreEqual(TestConstants.DisplayableId + "more", result.User.DisplayableId);
            Assert.AreEqual(TestConstants.IdentityProvider + "more", result.TenantId);

            Assert.IsTrue(HttpMessageHandlerFactory.IsMocksQueueEmpty, "All mocks should have been consumed");
        }
        public async Task AutoPromptBehaviorTestAsync()
        {
            MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success,
                                                                   TestConstants.DefaultRedirectUri + "?code=some-code"));

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant))
            {
                Method          = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(),
                PostData        = new Dictionary <string, string>()
                {
                    { "grant_type", "authorization_code" }
                }
            });

            var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, true, new TokenCache());
            AuthenticationResult result =
                await
                context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                          TestConstants.DefaultRedirectUri, new PlatformParameters(PromptBehavior.Auto)).ConfigureAwait(false);

            Assert.IsNotNull(result);
            Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, context.Authenticator.Authority);
            Assert.AreEqual("some-access-token", result.AccessToken);
            Assert.IsNotNull(result.UserInfo);
            Assert.AreEqual(TestConstants.DefaultDisplayableId, result.UserInfo.DisplayableId);
            Assert.AreEqual(TestConstants.DefaultUniqueId, result.UserInfo.UniqueId);
            // There should be one cached entry.
            Assert.AreEqual(1, context.TokenCache.Count);
        }
Beispiel #3
0
        public async Task AuthenticationContextAuthorityValidationTestAsync()
        {
            AuthenticationContext context = null;
            AuthenticationResult  result  = null;

            try
            {
                context = new AuthenticationContext("https://login.contoso.com/adfs");
                await
                context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                          TestConstants.DefaultRedirectUri, platformParameters);
            }
            catch (ArgumentException ex)
            {
                Assert.AreEqual(ex.ParamName, "validateAuthority");
            }

            MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success,
                                                                   TestConstants.DefaultRedirectUri + "?code=some-code"));
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler()
            {
                Method          = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage()
            });

            //whitelisted authority
            context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, true);
            result  =
                await
                context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                          TestConstants.DefaultRedirectUri, platformParameters,
                                          new UserIdentifier(TestConstants.DefaultDisplayableId, UserIdentifierType.RequiredDisplayableId));

            Assert.IsNotNull(result);
            Assert.AreEqual(result.AccessToken, "some-access-token");
            Assert.IsNotNull(result.UserInfo);
            //add handler to return failed discovery response
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler()
            {
                Method          = HttpMethod.Get,
                ResponseMessage =
                    MockHelpers.CreateFailureResponseMessage(
                        "{\"error\":\"invalid_instance\",\"error_description\":\"AADSTS70002: Error in validating authority.\"}")
            });

            try
            {
                context = new AuthenticationContext("https://login.microsoft0nline.com/common");
                result  =
                    await
                    context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                              TestConstants.DefaultRedirectUri, platformParameters);
            }
            catch (AdalException ex)
            {
                Assert.AreEqual(ex.ErrorCode, AdalError.AuthorityNotInValidList);
            }
        }
        public async Task ForcePromptForSelectAccountPromptBehaviorTestAsync()
        {
            MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success,
                                                                   TestConstants.DefaultRedirectUri + "?code=some-code"),
                                           // validate that authorizationUri passed to WebUi contains prompt=select_account query parameter
                                           new Dictionary <string, string> {
                { "prompt", "select_account" }
            });

            var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, true, new TokenCache());

            await context.TokenCache.StoreToCacheAsync(new AuthenticationResultEx
            {
                RefreshToken       = "some-rt",
                ResourceInResponse = TestConstants.DefaultResource,
                Result             = new AuthenticationResult("Bearer", "existing-access-token",
                                                              DateTimeOffset.UtcNow + TimeSpan.FromMinutes(100))
                {
                    UserInfo =
                        new UserInfo()
                    {
                        DisplayableId = TestConstants.DefaultDisplayableId,
                        UniqueId      = TestConstants.DefaultUniqueId
                    }
                },
            },
                                                       TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User,
                                                       new CallState(new Guid())).ConfigureAwait(false);

            ResetInstanceDiscovery();

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant))
            {
                Method          = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(),
                PostData        = new Dictionary <string, string>
                {
                    { "grant_type", "authorization_code" }
                }
            });

            AuthenticationResult result =
                await
                context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                          TestConstants.DefaultRedirectUri, new PlatformParameters(PromptBehavior.SelectAccount)).ConfigureAwait(false);

            Assert.IsNotNull(result);
            Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, context.Authenticator.Authority);
            Assert.AreEqual("some-access-token", result.AccessToken);
            Assert.IsNotNull(result.UserInfo);
            Assert.AreEqual(TestConstants.DefaultDisplayableId, result.UserInfo.DisplayableId);
            Assert.AreEqual(TestConstants.DefaultUniqueId, result.UserInfo.UniqueId);

            // There should be only one cache entry.
            Assert.AreEqual(1, context.TokenCache.Count);
        }
        public async Task SovereignUserWorldWideAuthorityIntegrationTest()
        {
            // creating AuthenticationContext with common Authority
            var authenticationContext =
                new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, false, new TokenCache());

            // mock value for authentication returnedUriInput, with cloud_instance_name claim
            var authReturnedUriInputMock = TestConstants.DefaultRedirectUri + "?code=some-code" + "&" +
                                           TokenResponseClaim.CloudInstanceHost + "=" + SovereignAuthorityHost;

            MockHelpers.ConfigureMockWebUI(
                new AuthorizationResult(AuthorizationStatus.Success, authReturnedUriInputMock),
                // validate that authorizationUri passed to WebUi contains instance_aware query parameter
                new Dictionary <string, string> {
                { "instance_aware", "true" }
            });

            HttpMessageHandlerFactory.AddMockHandler(MockHelpers.CreateInstanceDiscoveryMockHandler(TestConstants.GetDiscoveryEndpoint(TestConstants.DefaultAuthorityCommonTenant)));

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityBlackforestTenant))
            {
                Method          = HttpMethod.Post,
                ResponseMessage =
                    MockHelpers.CreateSuccessTokenResponseMessage(TestConstants.DefaultUniqueId,
                                                                  TestConstants.DefaultDisplayableId, TestConstants.DefaultResource),

                AdditionalRequestValidation = request =>
                {
                    // make sure that Sovereign authority was used for Authorization request
                    Assert.AreEqual(SovereignAuthorityHost, request.RequestUri.Authority);
                }
            });

            var authenticationResult = await authenticationContext.AcquireTokenAsync(TestConstants.DefaultResource,
                                                                                     TestConstants.DefaultClientId,
                                                                                     TestConstants.DefaultRedirectUri, _platformParameters, UserIdentifier.AnyUser, "instance_aware=true");

            // make sure that tenant specific sovereign Authority returned to the app in AuthenticationResult
            Assert.AreEqual(_sovereignTenantSpecificAuthority, authenticationResult.Authority);

            // make sure that AuthenticationContext Authority was updated
            Assert.AreEqual(_sovereignTenantSpecificAuthority, authenticationContext.Authority);

            // make sure AT was stored in the cache with tenant specific Sovereign Authority in the key
            Assert.AreEqual(1, authenticationContext.TokenCache.tokenCacheDictionary.Count);
            Assert.AreEqual(_sovereignTenantSpecificAuthority,
                            authenticationContext.TokenCache.tokenCacheDictionary.Keys.FirstOrDefault()?.Authority);

            // all mocks are consumed
            Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount());
        }
        public async Task AutoPromptBehaviorWithExpiredAccessTokenAndGoodRefreshTokenInCacheTestAsync()
        {
            MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success,
                                                                   TestConstants.DefaultRedirectUri + "?code=some-code"));

            var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, true, new TokenCache());

            await context.TokenCache.StoreToCacheAsync(new AuthenticationResultEx
            {
                RefreshToken       = "some-rt",
                ResourceInResponse = TestConstants.DefaultResource,
                Result             = new AuthenticationResult("Bearer", "existing-access-token", DateTimeOffset.UtcNow)
                {
                    UserInfo =
                        new UserInfo()
                    {
                        DisplayableId = TestConstants.DefaultDisplayableId,
                        UniqueId      = TestConstants.DefaultUniqueId
                    }
                },
            },
                                                       TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User,
                                                       new CallState(new Guid())).ConfigureAwait(false);

            ResetInstanceDiscovery();

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant))
            {
                Method          = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(),
                PostData        = new Dictionary <string, string>()
                {
                    { "grant_type", "refresh_token" }
                }
            });

            AuthenticationResult result =
                await
                context.AcquireTokenSilentAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                                new UserIdentifier(TestConstants.DefaultDisplayableId, UserIdentifierType.RequiredDisplayableId),
                                                new PlatformParameters(PromptBehavior.Auto)).ConfigureAwait(false);

            Assert.IsNotNull(result);
            Assert.AreEqual("some-access-token", result.AccessToken);

            // There should be only one cache entry.
            Assert.AreEqual(1, context.TokenCache.Count);
        }
Beispiel #7
0
        public async Task AcquireTokenWithAuthenticationCanceledTest()
        {
            var context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, new TokenCache());

            MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.UserCancel,
                                                                   TestConstants.DefaultRedirectUri + "?error=user_cancelled"));
            try
            {
                await
                context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                          TestConstants.DefaultRedirectUri, platformParameters);
            }
            catch (AdalServiceException ex)
            {
                Assert.AreEqual(ex.ErrorCode, AdalError.AuthenticationCanceled);
            }
        }
Beispiel #8
0
        public async Task AcquireTokenNoClientInfoReturnedTest()
        {
            PublicClientApplication app = new PublicClientApplication(TestConstants.ClientId);

            MockWebUI ui = new MockWebUI()
            {
                MockResult = new AuthorizationResult(AuthorizationStatus.Success,
                                                     TestConstants.AuthorityHomeTenant + "?code=some-code")
            };

            MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success,
                                                                   app.RedirectUri + "?code=some-code"));

            //add mock response for tenant endpoint discovery
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Get,
                ResponseMessage = MockHelpers.CreateOpenIdConfigurationResponse(TestConstants.AuthorityHomeTenant)
            });

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage("some-scope1 some-scope2",
                                                                                MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId), string.Empty)
            });

            try
            {
                AuthenticationResult result = await app.AcquireTokenAsync(TestConstants.Scope).ConfigureAwait(false);
            }
            catch (MsalClientException exc)
            {
                Assert.IsNotNull(exc);
                Assert.AreEqual(MsalClientException.JsonParseError, exc.ErrorCode);
                Assert.AreEqual("client info is null", exc.Message);
            }
            finally
            {
                Assert.IsTrue(HttpMessageHandlerFactory.IsMocksQueueEmpty, "All mocks should have been consumed");
            }
        }
Beispiel #9
0
        public async Task AcquireTokenPositiveWithNullCacheTest()
        {
            MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success,
                                                                   TestConstants.DefaultRedirectUri + "?code=some-code"));
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler()
            {
                Method          = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage()
            });

            var context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, null);
            AuthenticationResult result =
                await
                context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                          TestConstants.DefaultRedirectUri, platformParameters);

            Assert.IsNotNull(result);
            Assert.AreEqual(result.AccessToken, "some-access-token");
            Assert.IsNotNull(result.UserInfo);
        }
Beispiel #10
0
        public async Task NoStateReturnedTest()
        {
            PublicClientApplication app = new PublicClientApplication(TestConstants.ClientId);

            MockWebUI ui = new MockWebUI()
            {
                AddStateInAuthorizationResult = false,
                MockResult = new AuthorizationResult(AuthorizationStatus.Success,
                                                     TestConstants.AuthorityHomeTenant + "?code=some-code")
            };

            MockHelpers.ConfigureMockWebUI(ui);

            //add mock response for tenant endpoint discovery
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Get,
                ResponseMessage = MockHelpers.CreateOpenIdConfigurationResponse(TestConstants.AuthorityHomeTenant)
            });

            try
            {
                AuthenticationResult result = await app.AcquireTokenAsync(TestConstants.Scope);

                Assert.Fail("API should have failed here");
            }
            catch (MsalClientException exc)
            {
                Assert.IsNotNull(exc);
                Assert.AreEqual(MsalClientException.StateMismatchError, exc.ErrorCode);
            }
            finally
            {
                Assert.IsTrue(HttpMessageHandlerFactory.IsMocksQueueEmpty, "All mocks should have been consumed");
            }
            Assert.IsNotNull(_myReceiver.EventsReceived.Find(anEvent =>  // Expect finding such an event
                                                             anEvent[EventBase.EventNameKey].EndsWith("api_event") && anEvent[ApiEvent.ApiIdKey] == "170" &&
                                                             anEvent[ApiEvent.WasSuccessfulKey] == "false" && anEvent[ApiEvent.ApiErrorCodeKey] == "state_mismatch"
                                                             ));
        }
Beispiel #11
0
        public async Task AcquireTokenPositiveWithoutUserIdAsync()
        {
            var context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, new TokenCache());

            MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success,
                                                                   TestConstants.DefaultRedirectUri + "?code=some-code"));
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler()
            {
                Method          = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage()
            });

            AuthenticationResult result =
                await
                context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                          TestConstants.DefaultRedirectUri, platformParameters);

            Assert.IsNotNull(result);
            Assert.AreEqual(result.AccessToken, "some-access-token");
            try
            {
                result =
                    await
                    context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                              TestConstants.DefaultRedirectUri, platformParameters, null);
            }
            catch (ArgumentException exc)
            {
                Assert.IsTrue(exc.Message.StartsWith(AdalErrorMessage.SpecifyAnyUser));
            }

            // this should hit the cache
            result =
                await
                context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                          TestConstants.DefaultRedirectUri, platformParameters, UserIdentifier.AnyUser);

            Assert.IsNotNull(result);
            Assert.AreEqual(result.AccessToken, "some-access-token");
        }
Beispiel #12
0
        public async Task AuthUiFailedExceptionTest()
        {
            cache.ClientId = TestConstants.ClientId;
            PublicClientApplication app = new PublicClientApplication(TestConstants.ClientId)
            {
                UserTokenCache = cache
            };

            //add mock response for tenant endpoint discovery
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Get,
                ResponseMessage = MockHelpers.CreateOpenIdConfigurationResponse(TestConstants.AuthorityHomeTenant)
            });

            // repeat interactive call and pass in the same user
            MockHelpers.ConfigureMockWebUI(new MockWebUI()
            {
                ExceptionToThrow =
                    new MsalClientException(MsalClientException.AuthenticationUiFailedError,
                                            "Failed to invoke webview", new Exception("some-inner-Exception"))
            });

            try
            {
                AuthenticationResult result = await app.AcquireTokenAsync(TestConstants.Scope);

                Assert.Fail("API should have failed here");
            }
            catch (MsalClientException exc)
            {
                Assert.IsNotNull(exc);
                Assert.AreEqual(MsalClientException.AuthenticationUiFailedError, exc.ErrorCode);
                Assert.AreEqual("some-inner-Exception", exc.InnerException.Message);
            }
            finally
            {
                Assert.IsTrue(HttpMessageHandlerFactory.IsMocksQueueEmpty, "All mocks should have been consumed");
            }
        }
Beispiel #13
0
        public async Task ForcePromptTestAsync()
        {
            MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success,
                                                                   TestConstants.DefaultRedirectUri + "?code=some-code"));
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler()
            {
                Method          = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(),
                PostData        = new Dictionary <string, string>()
                {
                    { "grant_type", "authorization_code" }
                }
            });

            var           context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, true);
            TokenCacheKey key     = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                                                      TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User,
                                                      TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId);

            context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx
            {
                RefreshToken       = "some-rt",
                ResourceInResponse = TestConstants.DefaultResource,
                Result             = new AuthenticationResult("Bearer", "existing-access-token", DateTimeOffset.UtcNow)
            };

            AuthenticationResult result =
                await
                context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                          TestConstants.DefaultRedirectUri, new PlatformParameters(PromptBehavior.Always));

            Assert.IsNotNull(result);
            Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, context.Authenticator.Authority);
            Assert.AreEqual(result.AccessToken, "some-access-token");
            Assert.IsNotNull(result.UserInfo);
            Assert.AreEqual(TestConstants.DefaultDisplayableId, result.UserInfo.DisplayableId);
            Assert.AreEqual(TestConstants.DefaultUniqueId, result.UserInfo.UniqueId);
        }
Beispiel #14
0
        public async Task SmokeTest()
        {
            MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success,
                                                                   TestConstants.DefaultRedirectUri + "?code=some-code"));
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler()
            {
                Method          = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage()
            });

            var context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, true);
            AuthenticationResult result =
                await
                context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                          TestConstants.DefaultRedirectUri, platformParameters);

            Assert.IsNotNull(result);
            Assert.IsTrue(context.Authenticator.Authority.EndsWith("/some-tenant-id/"));
            Assert.AreEqual(result.AccessToken, "some-access-token");
            Assert.IsNotNull(result.UserInfo);
            Assert.AreEqual(TestConstants.DefaultDisplayableId, result.UserInfo.DisplayableId);
            Assert.AreEqual(TestConstants.DefaultUniqueId, result.UserInfo.UniqueId);
        }
Beispiel #15
0
        public async Task DifferentStateReturnedTest()
        {
            PublicClientApplication app = new PublicClientApplication(TestConstants.ClientId);

            MockWebUI ui = new MockWebUI()
            {
                AddStateInAuthorizationResult = false,
                MockResult = new AuthorizationResult(AuthorizationStatus.Success,
                                                     TestConstants.AuthorityHomeTenant + "?code=some-code&state=mistmatched")
            };

            MockHelpers.ConfigureMockWebUI(ui);

            //add mock response for tenant endpoint discovery
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Get,
                ResponseMessage = MockHelpers.CreateOpenIdConfigurationResponse(TestConstants.AuthorityHomeTenant)
            });

            try
            {
                AuthenticationResult result = await app.AcquireTokenAsync(TestConstants.Scope);

                Assert.Fail("API should have failed here");
            }
            catch (MsalClientException exc)
            {
                Assert.IsNotNull(exc);
                Assert.AreEqual(MsalClientException.StateMismatchError, exc.ErrorCode);
            }
            finally
            {
                Assert.IsTrue(HttpMessageHandlerFactory.IsMocksQueueEmpty, "All mocks should have been consumed");
            }
        }
Beispiel #16
0
        public void AcquireTokenDifferentUserReturnedFromServiceTest()
        {
            cache.ClientId = TestConstants.ClientId;
            PublicClientApplication app = new PublicClientApplication(TestConstants.ClientId)
            {
                UserTokenCache = cache
            };

            MockWebUI ui = new MockWebUI()
            {
                MockResult = new AuthorizationResult(AuthorizationStatus.Success,
                                                     TestConstants.AuthorityHomeTenant + "?code=some-code")
            };

            MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success,
                                                                   app.RedirectUri + "?code=some-code"));

            //add mock response for tenant endpoint discovery
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Get,
                ResponseMessage = MockHelpers.CreateOpenIdConfigurationResponse(TestConstants.AuthorityHomeTenant)
            });

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

            AuthenticationResult result = app.AcquireTokenAsync(TestConstants.Scope).Result;

            Assert.IsNotNull(result);
            Assert.IsNotNull(result.User);
            Assert.AreEqual(TestConstants.UniqueId, result.UniqueId);
            Assert.AreEqual(TestConstants.CreateUserIdentifer(), result.User.Identifier);
            Assert.AreEqual(TestConstants.DisplayableId, result.User.DisplayableId);

            Assert.IsTrue(HttpMessageHandlerFactory.IsMocksQueueEmpty, "All mocks should have been consumed");

            var dict = new Dictionary <string, string>();

            dict[OAuth2Parameter.DomainReq] = TestConstants.Utid;
            dict[OAuth2Parameter.LoginReq]  = TestConstants.Uid;

            // repeat interactive call and pass in the same user
            MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success,
                                                                   app.RedirectUri + "?code=some-code"), dict);

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(TestConstants.Scope.AsSingleString(),
                                                                                MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
                                                                                MockHelpers.CreateClientInfo(TestConstants.Uid, TestConstants.Utid + "more"))
            });

            try
            {
                result = app.AcquireTokenAsync(TestConstants.Scope, result.User, UIBehavior.SelectAccount, null).Result;
                Assert.Fail("API should have failed here");
            }
            catch (AggregateException ex)
            {
                MsalServiceException exc = (MsalServiceException)ex.InnerException;
                Assert.IsNotNull(exc);
                Assert.AreEqual("user_mismatch", exc.ErrorCode);
            }
            Assert.IsNotNull(_myReceiver.EventsReceived.Find(anEvent =>  // Expect finding such an event
                                                             anEvent[EventBase.EventNameKey].EndsWith("api_event") && anEvent[ApiEvent.ApiIdKey] == "174" &&
                                                             anEvent[ApiEvent.WasSuccessfulKey] == "false" && anEvent[ApiEvent.ApiErrorCodeKey] == "user_mismatch"
                                                             ));

            Assert.AreEqual(1, app.Users.Count());
            Assert.AreEqual(1, cache.TokenCacheAccessor.AccessTokenCacheDictionary.Count);

            Assert.IsTrue(HttpMessageHandlerFactory.IsMocksQueueEmpty, "All mocks should have been consumed");
        }
        public async Task AuthorityNotInInstanceCache_InstanceDiscoverCallMadeTestAsync()
        {
            const string content = @"{
                            ""tenant_discovery_endpoint"":""https://login.microsoftonline.com/tenant/.well-known/openid-configuration"",
                            ""api-version"":""1.1"",
                            ""metadata"":[{
                                ""preferred_network"":""login.microsoftonline.com"",
                                ""preferred_cache"":""login.windows.net"",
                                ""aliases"":[
                                    ""login.microsoftonline.com"",
                                    ""login.windows.net"",
                                    ""login.microsoft.com"",
                                    ""sts.windows.net""]}]}";

            // creating AuthenticationContext with common Authority
            var authenticationContext =
                new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, false, new TokenCache());

            // mock value for authentication returnedUriInput, with cloud_instance_name claim
            var authReturnedUriInputMock = TestConstants.DefaultRedirectUri + "?code=some-code" + "&" +
                                           TokenResponseClaim.CloudInstanceHost + "=" + SovereignAuthorityHost;

            MockHelpers.ConfigureMockWebUI(
                new AuthorizationResult(AuthorizationStatus.Success, authReturnedUriInputMock),
                // validate that authorizationUri passed to WebUi contains instance_aware query parameter
                new Dictionary <string, string> {
                { "instance_aware", "true" }
            });

            HttpMessageHandlerFactory.AddMockHandler(MockHelpers.CreateInstanceDiscoveryMockHandler(TestConstants.GetDiscoveryEndpoint(TestConstants.DefaultAuthorityCommonTenant), content));

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetDiscoveryEndpoint(TestConstants.DefaultAuthorityBlackforestTenant))
            {
                Method          = HttpMethod.Get,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(content)
                }
            });

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityBlackforestTenant))
            {
                Method          = HttpMethod.Post,
                ResponseMessage =
                    MockHelpers.CreateSuccessTokenResponseMessage(TestConstants.DefaultUniqueId,
                                                                  TestConstants.DefaultDisplayableId, TestConstants.DefaultResource)
            });

            // Assure instance cache is empty
            Assert.AreEqual(0, InstanceDiscovery.InstanceCache.Count());

            await authenticationContext.AcquireTokenAsync(TestConstants.DefaultResource,
                                                          TestConstants.DefaultClientId,
                                                          TestConstants.DefaultRedirectUri, _platformParameters, UserIdentifier.AnyUser, "instance_aware=true");

            // make sure AT was stored in the cache with tenant specific Sovereign Authority in the key
            Assert.AreEqual(1, authenticationContext.TokenCache.tokenCacheDictionary.Count);
            Assert.AreEqual(_sovereignTenantSpecificAuthority,
                            authenticationContext.TokenCache.tokenCacheDictionary.Keys.FirstOrDefault()?.Authority);

            // DE cloud authority now included in instance cache
            Assert.AreEqual(5, InstanceDiscovery.InstanceCache.Count());
            Assert.AreEqual(true, InstanceDiscovery.InstanceCache.Keys.Contains("login.microsoftonline.de"));
            Assert.AreEqual(true, InstanceDiscovery.InstanceCache.Keys.Contains("login.windows.net"));
            Assert.AreEqual(false, InstanceDiscovery.InstanceCache.Keys.Contains("login.partner.microsoftonline.cn"));

            // all mocks are consumed
            Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount());
        }
Beispiel #18
0
        public void AcquireTokenNullUserPassedInAndNewUserReturnedFromServiceTest()
        {
            cache.ClientId = TestConstants.ClientId;
            PublicClientApplication app = new PublicClientApplication(TestConstants.ClientId)
            {
                UserTokenCache = cache
            };

            MockWebUI ui = new MockWebUI()
            {
                MockResult = new AuthorizationResult(AuthorizationStatus.Success,
                                                     TestConstants.AuthorityHomeTenant + "?code=some-code")
            };

            MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success,
                                                                   app.RedirectUri + "?code=some-code"));

            //add mock response for tenant endpoint discovery
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Get,
                ResponseMessage = MockHelpers.CreateOpenIdConfigurationResponse(TestConstants.AuthorityHomeTenant)
            });

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

            AuthenticationResult result = app.AcquireTokenAsync(TestConstants.Scope).Result;

            Assert.IsNotNull(result);
            Assert.IsNotNull(result.User);
            Assert.AreEqual(TestConstants.UniqueId, result.UniqueId);
            Assert.AreEqual(TestConstants.CreateUserIdentifer(), result.User.Identifier);
            Assert.AreEqual(TestConstants.DisplayableId, result.User.DisplayableId);
            Assert.IsTrue(HttpMessageHandlerFactory.IsMocksQueueEmpty, "All mocks should have been consumed");

            // repeat interactive call and pass in the same user
            MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success,
                                                                   app.RedirectUri + "?code=some-code"));

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(TestConstants.Scope.AsSingleString(),
                                                                                MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
                                                                                MockHelpers.CreateClientInfo(TestConstants.Uid, TestConstants.Utid + "more"))
            });

            result = app.AcquireTokenAsync(TestConstants.Scope, (IUser)null, UIBehavior.SelectAccount, null).Result;
            Assert.IsNotNull(result);
            Assert.IsNotNull(result.User);
            Assert.AreEqual(TestConstants.UniqueId, result.UniqueId);
            Assert.AreEqual(TestConstants.CreateUserIdentifer(TestConstants.Uid, TestConstants.Utid + "more"),
                            result.User.Identifier);
            Assert.AreEqual(TestConstants.DisplayableId, result.User.DisplayableId);
            Assert.AreEqual(2, app.Users.Count());
            Assert.AreEqual(2, cache.TokenCacheAccessor.AccessTokenCacheDictionary.Count);
            Assert.IsTrue(HttpMessageHandlerFactory.IsMocksQueueEmpty, "All mocks should have been consumed");
        }