private async Task <AuthorizationResult> AcquireAuthCodeAsync( string redirectUri = TestRedirectUri, string requestUri = TestAuthorizationRequestUri, string responseUriString = TestAuthorizationResponseUri) { // Arrange var requestContext = new RequestContext(TestCommon.CreateDefaultServiceBundle(), Guid.NewGuid()); var responseUri = new Uri(responseUriString); IWebUI webUI = new DefaultOsBrowserWebUi(_platformProxy, _logger, _tcpInterceptor); _tcpInterceptor.ListenToSingleRequestAndRespondAsync( TestPort, Arg.Any <Func <Uri, string> >(), CancellationToken.None) .Returns(Task.FromResult(responseUri)); // Act AuthorizationResult authorizationResult = await webUI.AcquireAuthorizationAsync( new Uri(requestUri), new Uri(redirectUri), requestContext, CancellationToken.None).ConfigureAwait(false); // Assert that we opened the browser await _platformProxy.Received(1).StartDefaultOsBrowserAsync(requestUri) .ConfigureAwait(false); return(authorizationResult); }
[TestCategory(TestCategories.Regression)] //#1773 public async Task HttpListenerException_Cancellation_Async() { var webUI = CreateTestWebUI(); var requestContext = new RequestContext(TestCommon.CreateDefaultServiceBundle(), Guid.NewGuid()); CancellationTokenSource cts = new CancellationTokenSource(); _tcpInterceptor.When(x => x.ListenToSingleRequestAndRespondAsync( TestPort, "/", Arg.Any <Func <Uri, MessageAndHttpCode> >(), cts.Token)) .Do(x => { cts.Cancel(); throw new HttpListenerException(); }); // Act await AssertException.TaskThrowsAsync <OperationCanceledException>( () => webUI.AcquireAuthorizationAsync( new Uri(TestAuthorizationRequestUri), new Uri(TestRedirectUri), requestContext, cts.Token)) .ConfigureAwait(false); }
public async Task SaveAccessAndRefreshTokenWithEmptyCacheTestAsync() { var serviceBundle = TestCommon.CreateDefaultServiceBundle(); ITokenCacheInternal cache = new TokenCache(serviceBundle); MsalTokenResponse response = TestConstants.CreateMsalTokenResponse(); var requestParams = CreateAuthenticationRequestParameters(serviceBundle); requestParams.TenantUpdatedCanonicalAuthority = TestConstants.AuthorityTestTenant; AddHostToInstanceCache(serviceBundle, TestConstants.ProductionPrefNetworkEnvironment); await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(false); cache.Accessor.AssertItemCount( expectedAtCount: 1, expectedRtCount: 1, expectedAccountCount: 1, expectedIdtCount: 1, expectedAppMetadataCount: 1); var metadata = cache.Accessor.GetAllAppMetadata().First(); Assert.AreEqual(TestConstants.ClientId, metadata.ClientId); Assert.AreEqual(TestConstants.ProductionPrefNetworkEnvironment, metadata.Environment); Assert.IsNull(metadata.FamilyId); }
public async Task SaveAccessAndRefreshTokenWithIntersectingScopesTestAsync() { var serviceBundle = TestCommon.CreateDefaultServiceBundle(); ITokenCacheInternal cache = new TokenCache(serviceBundle); MsalTokenResponse response = TestConstants.CreateMsalTokenResponse(); var requestParams = CreateAuthenticationRequestParameters(serviceBundle); requestParams.TenantUpdatedCanonicalAuthority = TestConstants.AuthorityTestTenant; AddHostToInstanceCache(serviceBundle, TestConstants.ProductionPrefNetworkEnvironment); await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(false); response = TestConstants.CreateMsalTokenResponse(); response.Scope = TestConstants.s_scope.AsSingleString() + " random-scope"; response.AccessToken = "access-token-2"; response.RefreshToken = "refresh-token-2"; await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(false); Assert.AreEqual(1, cache.Accessor.GetAllRefreshTokens().Count()); Assert.AreEqual(1, cache.Accessor.GetAllAccessTokens().Count()); Assert.AreEqual("refresh-token-2", (await cache.GetAllRefreshTokensAsync(true).ConfigureAwait(false)).First().Secret); Assert.AreEqual("access-token-2", (await cache.GetAllAccessTokensAsync(true).ConfigureAwait(false)).First().Secret); }
public async Task SaveAccessAndRefreshTokenWithDifferentAuthoritySameUserTestAsync() { var serviceBundle = TestCommon.CreateDefaultServiceBundle(); ITokenCacheInternal cache = new TokenCache(serviceBundle); MsalTokenResponse response = TestConstants.CreateMsalTokenResponse(); var requestParams = CreateAuthenticationRequestParameters(serviceBundle); requestParams.TenantUpdatedCanonicalAuthority = TestConstants.AuthorityHomeTenant; AddHostToInstanceCache(serviceBundle, TestConstants.ProductionPrefNetworkEnvironment); await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(false); response = TestConstants.CreateMsalTokenResponse(); response.Scope = TestConstants.s_scope.AsSingleString() + " another-scope"; response.AccessToken = "access-token-2"; response.RefreshToken = "refresh-token-2"; requestParams = CreateAuthenticationRequestParameters(serviceBundle); requestParams.TenantUpdatedCanonicalAuthority = TestConstants.AuthorityGuestTenant; cache.SetAfterAccess(AfterAccessChangedNotification); await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(false); #pragma warning disable CS0618 // Type or member is obsolete Assert.IsFalse(((TokenCache)cache).HasStateChanged); #pragma warning restore CS0618 // Type or member is obsolete Assert.AreEqual(1, cache.Accessor.GetAllRefreshTokens().Count()); Assert.AreEqual(2, cache.Accessor.GetAllAccessTokens().Count()); Assert.AreEqual("refresh-token-2", (await cache.GetAllRefreshTokensAsync(true).ConfigureAwait(false)).First().Secret); }
public async Task DefaultOsBrowserWebUi_CustomBrowser_Async() { bool customOpenBrowserCalled = false; var options = new SystemWebViewOptions() { OpenBrowserAsync = (Uri u) => { customOpenBrowserCalled = true; return(Task.FromResult(0)); } }; var webUI = CreateTestWebUI(options); var requestContext = new RequestContext(TestCommon.CreateDefaultServiceBundle(), Guid.NewGuid()); var responseUri = new Uri(TestAuthorizationResponseUri); _tcpInterceptor.ListenToSingleRequestAndRespondAsync( TestPort, "/", Arg.Any <Func <Uri, MessageAndHttpCode> >(), CancellationToken.None) .Returns(Task.FromResult(responseUri)); // Act AuthorizationResult authorizationResult = await webUI.AcquireAuthorizationAsync( new Uri(TestAuthorizationRequestUri), new Uri(TestRedirectUri), requestContext, CancellationToken.None).ConfigureAwait(false); // Assert that we didn't open the browser using platform proxy await _platformProxy.DidNotReceiveWithAnyArgs().StartDefaultOsBrowserAsync(default, requestContext.ServiceBundle.Config.IsBrokerEnabled)
public void CanonicalAuthorityInitTest() { var serviceBundle = TestCommon.CreateDefaultServiceBundle(); const string UriNoPort = TestConstants.B2CAuthority; const string UriNoPortTailSlash = TestConstants.B2CAuthority; const string UriDefaultPort = "https://login.microsoftonline.in:443/tfp/tenant/policy"; const string UriCustomPort = "https://login.microsoftonline.in:444/tfp/tenant/policy"; const string UriCustomPortTailSlash = "https://login.microsoftonline.in:444/tfp/tenant/policy/"; const string UriVanityPort = TestConstants.B2CLoginAuthority; var authority = new B2CAuthority(serviceBundle, new AuthorityInfo(AuthorityType.B2C, UriNoPort, true)); Assert.AreEqual(UriNoPortTailSlash, authority.AuthorityInfo.CanonicalAuthority); authority = new B2CAuthority(serviceBundle, new AuthorityInfo(AuthorityType.B2C, UriDefaultPort, true)); Assert.AreEqual(UriNoPortTailSlash, authority.AuthorityInfo.CanonicalAuthority); authority = new B2CAuthority(serviceBundle, new AuthorityInfo(AuthorityType.B2C, UriCustomPort, true)); Assert.AreEqual(UriCustomPortTailSlash, authority.AuthorityInfo.CanonicalAuthority); authority = new B2CAuthority(serviceBundle, new AuthorityInfo(AuthorityType.B2C, UriVanityPort, true)); Assert.AreEqual(UriVanityPort, authority.AuthorityInfo.CanonicalAuthority); }
public void TestInitialize() { TestCommon.ResetInternalStaticCaches(); _credentialPathManager = new FileSystemCredentialPathManager(TestCommon.CreateDefaultServiceBundle().PlatformProxy.CryptographyManager); _mockFileIO = new MockFileIO(); _storageWorker = new PathStorageWorker(_mockFileIO, _credentialPathManager); }
public async Task SerializeDeserializeCacheTestAsync() { var serviceBundle = TestCommon.CreateDefaultServiceBundle(); ITokenCacheInternal cache = new TokenCache(serviceBundle); MsalTokenResponse response = TestConstants.CreateMsalTokenResponse(); var requestContext = new RequestContext(serviceBundle, Guid.NewGuid()); var requestParams = CreateAuthenticationRequestParameters(serviceBundle, requestContext: requestContext); requestParams.TenantUpdatedCanonicalAuthority = Authority.CreateAuthorityWithTenant( requestParams.AuthorityInfo, TestConstants.Utid); AddHostToInstanceCache(serviceBundle, TestConstants.ProductionPrefNetworkEnvironment); await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(false); byte[] serializedCache = ((ITokenCacheSerializer)cache).SerializeMsalV3(); cache.Accessor.ClearAccessTokens(); cache.Accessor.ClearRefreshTokens(); Assert.AreEqual(0, cache.Accessor.GetAllRefreshTokens().Count()); Assert.AreEqual(0, cache.Accessor.GetAllAccessTokens().Count()); ((ITokenCacheSerializer)cache).DeserializeMsalV3(serializedCache); Assert.AreEqual(1, cache.Accessor.GetAllRefreshTokens().Count()); Assert.AreEqual(1, cache.Accessor.GetAllAccessTokens().Count()); serializedCache = ((ITokenCacheSerializer)cache).SerializeMsalV3(); ((ITokenCacheSerializer)cache).DeserializeMsalV3(serializedCache); // item count should not change because old cache entries should have // been overriden Assert.AreEqual(1, cache.Accessor.GetAllRefreshTokens().Count()); Assert.AreEqual(1, cache.Accessor.GetAllAccessTokens().Count()); var atItem = (await cache.GetAllAccessTokensAsync(true).ConfigureAwait(false)).First(); Assert.AreEqual(response.AccessToken, atItem.Secret); Assert.AreEqual(TestConstants.AuthorityTestTenant, atItem.Authority); Assert.AreEqual(TestConstants.ClientId, atItem.ClientId); Assert.AreEqual(response.Scope, atItem.ScopeSet.AsSingleString()); // todo add test for idToken serialization // Assert.AreEqual(response.IdToken, atItem.RawIdToken); var rtItem = (await cache.GetAllRefreshTokensAsync(true).ConfigureAwait(false)).First(); Assert.AreEqual(response.RefreshToken, rtItem.Secret); Assert.AreEqual(TestConstants.ClientId, rtItem.ClientId); Assert.AreEqual(TestConstants.s_userIdentifier, rtItem.HomeAccountId); Assert.AreEqual(TestConstants.ProductionPrefNetworkEnvironment, rtItem.Environment); }
public override void TestInitialize() { base.TestInitialize(); var serviceBundle = TestCommon.CreateDefaultServiceBundle(); _cachePathStorage = new InMemoryCachePathStorage(); _credentialPathManager = new FileSystemCredentialPathManager(serviceBundle.PlatformProxy.CryptographyManager); _storageWorker = new PathStorageWorker(_cachePathStorage, _credentialPathManager); _storageManager = new StorageManager(serviceBundle.PlatformProxy, _storageWorker); }
public void CanDeserializeTokenCacheInNet462() { var tokenCache = new TokenCache(TestCommon.CreateDefaultServiceBundle()) { AfterAccess = args => { Assert.IsFalse(args.HasStateChanged); } }; ((ITokenCacheSerializer)tokenCache).DeserializeMsalV3(null); #pragma warning disable CS0618 // Type or member is obsolete Assert.IsFalse(tokenCache.HasStateChanged, "State should not have changed when deserializing nothing."); #pragma warning restore CS0618 // Type or member is obsolete }
public void NotEnoughPathSegmentsTest() { try { var serviceBundle = TestCommon.CreateDefaultServiceBundle(); var instance = Authority.CreateAuthority("https://login.microsoftonline.in/tfp/"); Assert.IsNotNull(instance); Assert.AreEqual(instance.AuthorityInfo.AuthorityType, AuthorityType.B2C); Assert.Fail("test should have failed"); } catch (Exception exc) { Assert.IsInstanceOfType(exc, typeof(ArgumentException)); Assert.AreEqual(MsalErrorMessage.B2cAuthorityUriInvalidPath, exc.Message); } }
public async Task UnknownNodesTestAsync() { string jsonFilePath = ResourceHelper.GetTestResourceRelativePath("CacheFromTheFuture.json"); string jsonContent = File.ReadAllText(jsonFilePath); byte[] cache = Encoding.UTF8.GetBytes(jsonContent); var tokenCache = new TokenCache(TestCommon.CreateDefaultServiceBundle(), false); tokenCache.SetBeforeAccess(notificationArgs => { notificationArgs.TokenCache.DeserializeMsalV3(cache); }); tokenCache.SetAfterAccess(notificationArgs => { cache = notificationArgs.TokenCache.SerializeMsalV3(); }); var notification = new TokenCacheNotificationArgs(tokenCache, null, null, false, false, null, false, null, default, default);
private static void ValidateCommonQueryParams( Dictionary <string, string> qp, string redirectUri = MsalTestConstants.RedirectUri) { Assert.IsNotNull(qp); Assert.IsTrue(qp.ContainsKey("client-request-id")); Assert.AreEqual(MsalTestConstants.ClientId, qp["client_id"]); Assert.AreEqual("code", qp["response_type"]); Assert.AreEqual(redirectUri, qp["redirect_uri"]); Assert.AreEqual(MsalTestConstants.DisplayableId, qp["login_hint"]); Assert.AreEqual(Prompt.SelectAccount.PromptValue, qp["prompt"]); Assert.AreEqual(TestCommon.CreateDefaultServiceBundle().PlatformProxy.GetProductName(), qp["x-client-sku"]); Assert.IsFalse(string.IsNullOrEmpty(qp["x-client-ver"])); Assert.IsFalse(string.IsNullOrEmpty(qp["x-client-os"])); #if !NET_CORE Assert.IsFalse(string.IsNullOrEmpty(qp["x-client-cpu"])); #endif }
public void CanonicalAuthorityInitTest() { var serviceBundle = TestCommon.CreateDefaultServiceBundle(); const string UriNoPort = "https://login.microsoftonline.in/mytenant.com"; const string UriNoPortTailSlash = "https://login.microsoftonline.in/mytenant.com/"; const string UriDefaultPort = "https://login.microsoftonline.in:443/mytenant.com"; const string UriCustomPort = "https://login.microsoftonline.in:444/mytenant.com"; const string UriCustomPortTailSlash = "https://login.microsoftonline.in:444/mytenant.com/"; var authority = Authority.CreateAuthority(UriNoPort); Assert.AreEqual(UriNoPortTailSlash, authority.AuthorityInfo.CanonicalAuthority); authority = Authority.CreateAuthority(UriDefaultPort); Assert.AreEqual(UriNoPortTailSlash, authority.AuthorityInfo.CanonicalAuthority); authority = Authority.CreateAuthority(UriCustomPort); Assert.AreEqual(UriCustomPortTailSlash, authority.AuthorityInfo.CanonicalAuthority); }
public void FindAccessToken_ScopeCaseInsensitive() { var serviceBundle = TestCommon.CreateDefaultServiceBundle(); ITokenCacheInternal cache = new TokenCache(serviceBundle); _tokenCacheHelper.PopulateCacheWithOneAccessToken(cache.Accessor); var requestParams = CreateAuthenticationRequestParameters(serviceBundle, scopes: new SortedSet <string>()); requestParams.Account = TestConstants.s_user; string scopeInCache = TestConstants.s_scope.FirstOrDefault(); string upperCaseScope = scopeInCache.ToUpperInvariant(); requestParams.Scope.Add(upperCaseScope); var item = cache.FindAccessTokenAsync(requestParams).Result; Assert.IsNotNull(item); Assert.IsTrue(item.ScopeSet.Contains(scopeInCache)); }
public void NotEnoughPathSegmentsTest() { try { var serviceBundle = TestCommon.CreateDefaultServiceBundle(); var instance = Authority.CreateAuthority("https://login.microsoftonline.in/tfp/"); Assert.IsNotNull(instance); Assert.AreEqual(instance.AuthorityInfo.AuthorityType, AuthorityType.B2C); var resolver = new AuthorityResolutionManager(); var endpoints = resolver.ResolveEndpoints( instance, null, new RequestContext(serviceBundle, Guid.NewGuid())); Assert.Fail("test should have failed"); } catch (Exception exc) { Assert.IsInstanceOfType(exc, typeof(ArgumentException)); Assert.AreEqual(MsalErrorMessage.B2cAuthorityUriInvalidPath, exc.Message); } }
public void CacheB2CTokenTest() { var serviceBundle = TestCommon.CreateDefaultServiceBundle(); ITokenCacheInternal cache = new TokenCache(serviceBundle); string tenantID = "someTenantID"; var authority = Authority.CreateAuthority( serviceBundle, $"https://login.microsoftonline.com/tfp/{tenantID}/somePolicy/oauth2/v2.0/authorize"); // creating IDToken with empty tenantID and displayableID/PreferredUserName for B2C scenario MsalTokenResponse response = MsalTestConstants.CreateMsalTokenResponse(); var requestContext = RequestContext.CreateForTest(serviceBundle); var requestParams = CreateAuthenticationRequestParameters(serviceBundle, authority, requestContext: requestContext); requestParams.TenantUpdatedCanonicalAuthority = MsalTestConstants.AuthorityTestTenant; cache.SaveTokenResponseAsync(requestParams, response); Assert.AreEqual(1, cache.Accessor.GetAllRefreshTokens().Count()); Assert.AreEqual(1, cache.Accessor.GetAllAccessTokens().Count()); }
public async Task SaveMultipleAppmetadataAsync() { var serviceBundle = TestCommon.CreateDefaultServiceBundle(); ITokenCacheInternal cache = new TokenCache(serviceBundle); MsalTokenResponse response = TestConstants.CreateMsalTokenResponse(); MsalTokenResponse response2 = TestConstants.CreateMsalTokenResponse(); response2.FamilyId = "1"; var requestParams = CreateAuthenticationRequestParameters(serviceBundle); requestParams.TenantUpdatedCanonicalAuthority = Authority.CreateAuthorityWithTenant( requestParams.AuthorityInfo, TestConstants.Utid); AddHostToInstanceCache(serviceBundle, TestConstants.ProductionPrefNetworkEnvironment); await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(false); await cache.SaveTokenResponseAsync(requestParams, response2).ConfigureAwait(false); cache.Accessor.AssertItemCount( expectedAtCount: 1, expectedRtCount: 2, // a normal RT and an FRT expectedAccountCount: 1, expectedIdtCount: 1, expectedAppMetadataCount: 1); var metadata = cache.Accessor.GetAllAppMetadata().First(); Assert.AreEqual(TestConstants.ClientId, metadata.ClientId); Assert.AreEqual(TestConstants.ProductionPrefNetworkEnvironment, metadata.Environment); Assert.AreEqual(TestConstants.FamilyId, metadata.FamilyId); Assert.IsTrue(cache.Accessor.GetAllRefreshTokens().Any(rt => rt.FamilyId == "1")); Assert.IsTrue(cache.Accessor.GetAllRefreshTokens().Any(rt => string.IsNullOrEmpty(rt.FamilyId))); }
public async Task UnknownNodesTestAsync() { string jsonFilePath = ResourceHelper.GetTestResourceRelativePath("CacheFromTheFuture.json"); string jsonContent = File.ReadAllText(jsonFilePath); byte[] cache = Encoding.UTF8.GetBytes(jsonContent); var tokenCache = new TokenCache(TestCommon.CreateDefaultServiceBundle(), true); tokenCache.SetBeforeAccess(notificationArgs => { notificationArgs.TokenCache.DeserializeMsalV3(cache); }); tokenCache.SetAfterAccess(notificationArgs => { cache = notificationArgs.TokenCache.SerializeMsalV3(); }); var notification = new TokenCacheNotificationArgs(tokenCache, null, null, false, false, true, CancellationToken.None); await(tokenCache as ITokenCacheInternal).OnBeforeAccessAsync(notification).ConfigureAwait(false); await(tokenCache as ITokenCacheInternal).OnAfterAccessAsync(notification).ConfigureAwait(false); (tokenCache as ITokenCacheInternal).Accessor.AssertItemCount(5, 4, 3, 3, 3); await(tokenCache as ITokenCacheInternal).OnBeforeAccessAsync(notification).ConfigureAwait(false); (tokenCache as ITokenCacheInternal).Accessor.AssertItemCount(5, 4, 3, 3, 3); await(tokenCache as ITokenCacheInternal).OnAfterAccessAsync(notification).ConfigureAwait(false); (tokenCache as ITokenCacheInternal).Accessor.AssertItemCount(5, 4, 3, 3, 3); var finalJson = JObject.Parse(Encoding.UTF8.GetString(cache)); var originalJson = JObject.Parse(jsonContent); Assert.IsTrue(JToken.DeepEquals(originalJson, finalJson)); }
public void TestInitialize() { this._serviceBundle = TestCommon.CreateDefaultServiceBundle(); }
public void TestInitialize() { TestCommon.ResetInternalStaticCaches(); _serviceBundle = TestCommon.CreateDefaultServiceBundle(); }