public async Task MultiUserCacheCompatabilityTestAsync() { // Arrange //Acquire AT for default lab account LabResponse labResponseDefault = await LabUserHelper.GetDefaultUserAsync().ConfigureAwait(false); AuthenticationResult defaultAccountResult = await RunTestForUserAsync(labResponseDefault).ConfigureAwait(false); //Acquire AT for ADFS 2019 account LabResponse labResponseFederated = await LabUserHelper.GetAdfsUserAsync(FederationProvider.ADFSv2019, true).ConfigureAwait(false); var federatedAccountResult = await RunTestForUserAsync(labResponseFederated, false).ConfigureAwait(false); //Acquire AT for MSA account LabResponse labResponseMsa = await LabUserHelper.GetB2CMSAAccountAsync().ConfigureAwait(false); labResponseMsa.App.AppId = LabApiConstants.MSAOutlookAccountClientID; var msaAccountResult = await RunTestForUserAsync(labResponseMsa).ConfigureAwait(false); PublicClientApplication pca = PublicClientApplicationBuilder.Create(labResponseDefault.App.AppId).BuildConcrete(); AuthenticationResult authResult = await pca.AcquireTokenSilent(new[] { CoreUiTestConstants.DefaultScope }, defaultAccountResult.Account) .ExecuteAsync() .ConfigureAwait(false); Assert.IsNotNull(authResult); Assert.IsNotNull(authResult.AccessToken); Assert.IsNotNull(authResult.IdToken); pca = PublicClientApplicationBuilder.Create(labResponseFederated.App.AppId).BuildConcrete(); authResult = await pca.AcquireTokenSilent(new[] { CoreUiTestConstants.DefaultScope }, federatedAccountResult.Account) .ExecuteAsync() .ConfigureAwait(false); Assert.IsNotNull(authResult); Assert.IsNotNull(authResult.AccessToken); Assert.IsNull(authResult.IdToken); pca = PublicClientApplicationBuilder.Create(LabApiConstants.MSAOutlookAccountClientID).BuildConcrete(); authResult = await pca.AcquireTokenSilent(new[] { CoreUiTestConstants.DefaultScope }, msaAccountResult.Account) .ExecuteAsync() .ConfigureAwait(false); Assert.IsNotNull(authResult); Assert.IsNotNull(authResult.AccessToken); Assert.IsNull(authResult.IdToken); }
public async Task ManagedUsernamePasswordCommonAuthorityTestAsync() { using (var httpManager = new MockHttpManager()) { httpManager.AddInstanceDiscoveryMockHandler(); httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityCommonTenant); // user realm discovery httpManager.AddMockHandler( new MockHttpMessageHandler { ExpectedMethod = HttpMethod.Get, ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent( "{\"ver\":\"1.0\",\"account_type\":\"Managed\",\"domain_name\":\"id.com\"}") }, ExpectedQueryParams = new Dictionary <string, string> { { "api-version", "1.0" } } }); httpManager.AddMockHandler( new MockHttpMessageHandler { ExpectedMethod = HttpMethod.Post, ResponseMessage = MockHelpers.CreateInvalidRequestTokenResponseMessage() }); PublicClientApplication app = PublicClientApplicationBuilder.Create(MsalTestConstants.ClientId) .WithAuthority(new Uri(ClientApplicationBase.DefaultAuthority), true) .WithHttpManager(httpManager) .WithTelemetry(new TraceTelemetryConfig()) .BuildConcrete(); // Call acquire token MsalServiceException result = await AssertException.TaskThrowsAsync <MsalServiceException>( async() => await app.AcquireTokenByUsernamePassword( MsalTestConstants.Scope, MsalTestConstants.User.Username, _secureString).ExecuteAsync(CancellationToken.None).ConfigureAwait(false)).ConfigureAwait(false); // Check inner exception Assert.AreEqual(MsalError.InvalidRequest, result.ErrorCode); // There should be no cached entries. Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count()); } }
public static IPublicClientApplicationExecutor CreatePublicClientExecutor( PublicClientApplication publicClientApplication) { IPublicClientApplicationExecutor executor = new PublicClientExecutor( publicClientApplication.ServiceBundle, publicClientApplication); if (IsMatsEnabled(publicClientApplication)) { executor = new TelemetryPublicClientExecutor(executor, publicClientApplication.ServiceBundle.Mats); } return(executor); }
public async Task ATS_NonExpired_NeedsRefresh_AADUnavailableResponse_Async() { // Arrange using (MockHttpAndServiceBundle harness = base.CreateTestHarness()) { Trace.WriteLine("1. Setup an app with a token cache with one AT"); PublicClientApplication app = SetupPca(harness); Trace.WriteLine("2. Configure AT so that it shows it needs to be refreshed"); UpdateATWithRefreshOn(app.UserTokenCacheInternal.Accessor, DateTime.UtcNow - TimeSpan.FromMinutes(1)); TokenCacheAccessRecorder cacheAccess = app.UserTokenCache.RecordAccess(); Trace.WriteLine("3. Configure AAD to respond with a 500 error"); harness.HttpManager.AddAllMocks(TokenResponseType.Invalid_AADUnavailable503); harness.HttpManager.AddTokenResponse(TokenResponseType.Invalid_AADUnavailable503); // Act var account = new Account(TestConstants.s_userIdentifier, TestConstants.DisplayableId, null); AuthenticationResult result = await app .AcquireTokenSilent( TestConstants.s_scope.ToArray(), account) .ExecuteAsync(CancellationToken.None) .ConfigureAwait(false); // Assert Assert.IsNotNull(result, "ATS still succeeds even though AAD is unavaible"); Assert.AreEqual(0, harness.HttpManager.QueueSize); cacheAccess.AssertAccessCounts(1, 0); // the refresh failed, no new data is written to the cache // reset throttling, otherwise MSAL would block similar requests for 2 minutes // and we would still get a cached response SingletonThrottlingManager.GetInstance().ResetCache(); // Now let AAD respond with tokens harness.HttpManager.AddTokenResponse(TokenResponseType.Valid); result = await app .AcquireTokenSilent( TestConstants.s_scope.ToArray(), account) .ExecuteAsync(CancellationToken.None) .ConfigureAwait(false); Assert.IsNotNull(result); cacheAccess.AssertAccessCounts(2, 1); // new tokens written to cache } }
public async Task <AuthenticationResult> AcquireTokenSilentAsync() { // Create a public client app PublicClientApplication pca = new PublicClientApplication(Constants.ClientId, Constants.Authority); IEnumerable <IAccount> accounts = await pca.GetAccountsAsync(); var firstAccount = accounts.FirstOrDefault(); // Authenticate the user. var authenticationResult = await pca.AcquireTokenSilentAsync( Constants.Scopes, firstAccount); return(authenticationResult); }
public AuthorizationService(string appId, string authorityUrl, string editUrl, string resetUrl, string redirectUrl, string[] scopes, UIParent uiParent) { ApplicationId = appId; AuthorityUrl = authorityUrl; EditUrl = editUrl; ResetUrl = resetUrl; RedirectUrl = redirectUrl; Scopes = scopes; UiParent = uiParent; _publicClientApplication = new PublicClientApplication(ApplicationId, AuthorityUrl) { RedirectUri = RedirectUrl }; }
public void GetAccountsAndSignThemOutTest() { PublicClientApplication app = PublicClientApplicationBuilder.Create(MsalTestConstants.ClientId).BuildConcrete(); var tokenCacheHelper = new TokenCacheHelper(); tokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor); foreach (var user in app.GetAccountsAsync().Result) { app.RemoveAsync(user).Wait(); } Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count()); Assert.AreEqual(0, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count()); }
private static IAuthenticationProvider CreateAuthorizationProvider(IConfigurationRoot config) { var clientId = config["applicationId"]; var clientSecret = config["applicationSecret"]; var redirectUri = config["redirectUri"]; var authority = $"https://login.microsoftonline.com/{config["tenantId"]}"; List <string> scopes = new List <string>(); scopes.Add("https://graph.microsoft.com/.default"); var cca = new PublicClientApplication(clientId, authority); return(new DeviceCodeFlowAuthorizationProvider(cca, scopes)); }
public App() { InitializeComponent(); PCA = new PublicClientApplication(ClientId, Authority) { RedirectUri = $"com.onmicrosoft.vikelaproductsdev.Vikela.iOS://oauth/redirect" }; var _MasterRepo = MasterRepository.MasterRepo; _MasterRepo.SetRootView(new NavigationPage(new WelcomeView())); //_MasterRepo.SetRootView(new NavigationPage(new TestHarnesView())); MainPage = _MasterRepo.GetRootView(); }
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 async Task TelemetryCacheRefreshTestAsync() { using (_harness = CreateTestHarness()) { _harness.HttpManager.AddInstanceDiscoveryMockHandler(); _app = PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithHttpManager(_harness.HttpManager) .WithDefaultRedirectUri() .WithLogging((lvl, msg, pii) => Trace.WriteLine($"[MSAL_LOG][{lvl}] {msg}")) .BuildConcrete(); var tokenCacheHelper = new TokenCacheHelper(); tokenCacheHelper.PopulateCache(_app.UserTokenCacheInternal.Accessor, addSecondAt: false); Trace.WriteLine("Step 1. Acquire Token Interactive successful"); var result = await RunAcquireTokenInteractiveAsync(AcquireTokenInteractiveOutcome.Success).ConfigureAwait(false); AssertCurrentTelemetry(result.HttpRequest, ApiIds.AcquireTokenInteractive, forceRefresh: false); AssertPreviousTelemetry(result.HttpRequest, expectedSilentCount: 0); // Previous_request = 2|0||| Trace.WriteLine("Step 2. Acquire Token Silent successful - AT served from cache"); result = await RunAcquireTokenSilentAsync(AcquireTokenSilentOutcome.SuccessFromCache).ConfigureAwait(false); Assert.IsNull(result.HttpRequest, "No calls are made to the token endpoint"); Trace.WriteLine("Step 3. Acquire Token Silent successful - via expired token"); UpdateATWithRefreshOn(_app.UserTokenCacheInternal.Accessor, DateTime.UtcNow - TimeSpan.FromMinutes(1), true); TokenCacheAccessRecorder cacheAccess = _app.UserTokenCache.RecordAccess(); result = await RunAcquireTokenSilentAsync(AcquireTokenSilentOutcome.SuccessViaCacheRefresh).ConfigureAwait(false); AssertCurrentTelemetry(result.HttpRequest, ApiIds.AcquireTokenSilent, forceRefresh: false, isCacheSerialized: true, cacheRefresh: "1"); AssertPreviousTelemetry(result.HttpRequest, expectedSilentCount: 1); // Previous_request = 2|1||| Trace.WriteLine("Step 4. Acquire Token Silent successful - via refresh on"); UpdateATWithRefreshOn(_app.UserTokenCacheInternal.Accessor, DateTime.UtcNow - TimeSpan.FromMinutes(1)); cacheAccess = _app.UserTokenCache.RecordAccess(); result = await RunAcquireTokenSilentAsync(AcquireTokenSilentOutcome.SuccessViaCacheRefresh).ConfigureAwait(false); AssertCurrentTelemetry(result.HttpRequest, ApiIds.AcquireTokenSilent, forceRefresh: false, isCacheSerialized: true, cacheRefresh: "2"); AssertPreviousTelemetry(result.HttpRequest, expectedSilentCount: 0); // Previous_request = 2|1||| Trace.WriteLine("Step 5. Acquire Token Silent with force_refresh = true"); result = await RunAcquireTokenSilentAsync(AcquireTokenSilentOutcome.SuccessViaCacheRefresh, forceRefresh : true).ConfigureAwait(false); AssertCurrentTelemetry(result.HttpRequest, ApiIds.AcquireTokenSilent, forceRefresh: true, isCacheSerialized: true, cacheRefresh: "3"); // Current_request = 3 | ATS_ID, 1, 3 | AssertPreviousTelemetry(result.HttpRequest, expectedSilentCount: 0); // Previous_request = 2|0||| } }
protected override async void OnInitialized(EventArgs e) { base.OnInitialized(e); Scopes = new string[] { todoListServiceScope }; // Initialize the PublicClientApplication app = new PublicClientApplication(clientId, "https://login.microsoftonline.com/common/v2.0", TokenCacheHelper.GetUserCache()); AuthenticationResult result = null; // TODO: Check if the user is already signed in. // As the app starts, we want to check to see if the user is already signed in. // You can do so by trying to get a token from MSAL, using the method // AcquireTokenSilent. This forces MSAL to throw an exception if it cannot // get a token for the user without showing a UI. try { result = await app.AcquireTokenSilentAsync(Scopes, app.Users.FirstOrDefault()); // If we got here, a valid token is in the cache - or MSAL was able to get a new oen via refresh token. // Proceed to fetch the user's tasks from the TodoListService via the GetTodoList() method. SignInButton.Content = "Clear Cache"; GetTodoList(); } catch (MsalUiRequiredException) { // The app should take no action and simply show the user the sign in button. } catch (MsalException ex) { if (ex.ErrorCode == "failed_to_acquire_token_silently") { // If user interaction is required, the app should take no action, // and simply show the user the sign in button. } else { // Here, we catch all other MsalExceptions string message = ex.Message; if (ex.InnerException != null) { message += "Inner Exception : " + ex.InnerException.Message; } MessageBox.Show(message); } } }
public static void InitPublicClient() { MsalPublicClient = new PublicClientApplication(ClientId, Authority); switch (Device.RuntimePlatform) { case "iOS": MsalPublicClient.RedirectUri = RedirectUriOnIos; break; case "Android": MsalPublicClient.RedirectUri = RedirectUriOnAndroid; break; } MsalPublicClient.ValidateAuthority = ValidateAuthority; }
public async Task <string> GetTokenSilentAsync(IPlatformParameters parameters) { try { app = new PublicClientApplication("https://login.windows.net/common", "CLIENT_ID"); var result = await app.AcquireTokenSilentAsync(Sts.ValidScope, Sts.ValidUserName); return(result.Token); } catch (Exception ex) { string msg = ex.Message + "\n" + ex.StackTrace; return(msg); } }
private PublicClientApplication InitPcaFromCacheString( AzureCloudInstance cloud, HttpManager httpManager, string tokenCacheString) { PublicClientApplication pca = PublicClientApplicationBuilder .Create(ClientIdInFile) .WithAuthority(cloud, AadAuthorityAudience.PersonalMicrosoftAccount) .WithHttpManager(httpManager) .BuildConcrete(); pca.InitializeTokenCacheFromString(tokenCacheString); pca.UserTokenCacheInternal.Accessor.AssertItemCount(3, 3, 3, 3, 1); return(pca); }
public AuthService(AuthConfig authConfig, ILoggerProvider loggerProvider = null) { _authConfig = authConfig ?? throw new ArgumentNullException(nameof(authConfig)); _logger = loggerProvider?.GetLogger(); #if WINDOWS_APP_RUNTIME _appClient = new PublicClientApplication(authConfig.ClientId, _Authority); #else var tokenCacheService = new TokenCacheService("W8lessLabsGraphAPI"); _appClient = new PublicClientApplication(authConfig.ClientId, _Authority, tokenCacheService.TokenCache); #endif }
public static async Task <string> GetTokenIntegratedAuthAsync(Sts Sts) { try { PublicClientApplication app = new PublicClientApplication(Sts.Authority, "7c7a2f70-caef-45c8-9a6c-091633501de4"); var result = await app.AcquireTokenWithIntegratedAuthAsync(Sts.ValidScope); return(result.Token); } catch (Exception ex) { string msg = ex.Message + "\n" + ex.StackTrace; return(msg); } }
public MythicalExperienceClient(string AuthSource) { if (AuthSource == "aad") { _authSource = "aad"; PublicClientApp = new PublicClientApplication(ClientId, "https://login.microsoftonline.com/common", TokenCacheHelper.GetUserCache()); } else { _authSource = "b2c"; TokenCache tokenCache = TokenCacheHelper.GetUserCache(); Authority = BaseAuthority.Replace("{tenant}", Tenant).Replace("{policy}", AuthSource); //PublicClientApp = new PublicClientApplication(B2C_ClientId, Authority, tokenCache); PublicClientApp = new PublicClientApplication(B2C_ClientId, Authority); } }
private void EnsurePublicClientApplication(Dictionary <string, string> input) { if (_publicClientApplication != null) { return; } if (!input.ContainsKey("client_id")) { return; } _publicClientApplication = input.ContainsKey("authority") ? new PublicClientApplication(input["client_id"], input["authority"]) : new PublicClientApplication(input["client_id"]); }
public MainWindow() { InitializeComponent(); string clientId = "<<HRClient Client Id>>"; string tenantId = "<<YOUR TENANT ID>>"; //sample redirect uri : hrclient://auth string redirectUri = "<<HRClient Redirect URI>>"; _publicClientApp = new PublicClientApplication(clientId, $"https://login.microsoftonline.com/{tenantId}"); _publicClientApp.RedirectUri = redirectUri; }
public static async Task <string> GetTokenIntegratedAuthAsync(Sts Sts) { try { PublicClientApplication app = new PublicClientApplication(Sts.Authority, "269da09d-a3e8-4b9e-b0a3-18fdf67d7507"); var result = await app.AcquireTokenWithIntegratedAuthAsync(Sts.ValidScope); return(result.Token); } catch (Exception ex) { string msg = ex.Message + "\n" + ex.StackTrace; return(msg); } }
public void Init() { if (AuthClient != null) { return; } AuthClient = new PublicClientApplication(CommonConstants.ADApplicationID, CommonConstants.ADAuthority) { ValidateAuthority = false, RedirectUri = CommonConstants.ADRedirectID, }; }
public async Task HttpRequestExceptionIsNotSuppressed() { var app = new PublicClientApplication(TestConstants.ClientId); // add mock response bigger than 1MB for Http Client HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler { Method = HttpMethod.Get, ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(new string(new char[1048577])) } }); await app.AcquireTokenAsync(TestConstants.Scope.ToArray()); }
/// <summary> /// Initializes a new instance of the <see cref="T:Camera.App"/> class. /// </summary> public App() { // default redirectURI; each platform specific project will have to override it with its own PCA = new PublicClientApplication(Config.MediaServicesClientId, Authority); PCA.RedirectUri = $"msal{Config.MediaServicesClientId}://auth"; InitializeComponent(); // The Application ResourceDictionary is available in Xamarin.Forms 1.3 and later if (Current.Resources == null) { Current.Resources = new ResourceDictionary(); } MainPage = IoC.Resolve <NavigationPage>(); }
public static void Main(string[] args) { PublicClientApplication pca = new PublicClientApplication( ClientIdForPublicApp, Authority, TokenCacheHelper.GetUserCache()); // token cache serialization https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/token-cache-serialization Logger.LogCallback = Log; Logger.Level = LogLevel.Verbose; Logger.PiiLoggingEnabled = true; #if ARIA_TELEMETRY_ENABLED Telemetry.GetInstance().RegisterReceiver( (new Microsoft.Identity.Client.AriaTelemetryProvider.ServerTelemetryHandler()).OnEvents); #endif RunConsoleAppLogicAsync(pca).Wait(); }
/// <inheritdoc /> protected override async Task <CacheExecutorResults> InternalExecuteAsync(CommandLineOptions options) { var v1App = PreRegisteredApps.CommonCacheTestV1; string resource = PreRegisteredApps.MsGraph; string[] scopes = new[] { resource + "/user.read" }; Logger.LogCallback = (LogLevel level, string message, bool containsPii) => { Console.WriteLine("{0}: {1}", level, message); }; CommonCacheTestUtils.EnsureCacheFileDirectoryExists(); var tokenCache = new TokenCache(); FileBasedTokenCacheHelper.ConfigureUserCache( options.CacheStorageType, tokenCache, CommonCacheTestUtils.AdalV3CacheFilePath, CommonCacheTestUtils.MsalV2CacheFilePath); var app = new PublicClientApplication(v1App.ClientId, v1App.Authority, tokenCache) { ValidateAuthority = true }; IEnumerable <IAccount> accounts = await app.GetAccountsAsync().ConfigureAwait(false); try { var result = await app.AcquireTokenSilentAsync(scopes, accounts.FirstOrDefault(), app.Authority, false).ConfigureAwait(false); Console.WriteLine($"got token for '{result.Account.Username}' from the cache"); return(new CacheExecutorResults(result.Account.Username, true)); } catch (MsalUiRequiredException) { var result = await app.AcquireTokenByUsernamePasswordAsync(scopes, options.Username, options.UserPassword.ToSecureString()).ConfigureAwait(false); Console.WriteLine($"got token for '{result.Account.Username}' without the cache"); return(new CacheExecutorResults(result.Account.Username, false)); } }
/// <summary> /// Displays groups for a user and its organization /// WARNING: As of today, this application needs consent of an Azure AD administrator /// See https://developer.microsoft.com/en-us/graph/docs/concepts/known_issues /// </summary> /// <param name="args">unused</param> static void Main(string[] args) { // Get an access token PublicClientApplication app = new PublicClientApplication(clientId); string[] scopes = { "User.Read", "Group.Read.All", "Directory.Read.All", "Directory.AccessAsUser.All" }; // Instanciate the Microsoft Graph, and provides the way to acquire the token. GraphServiceClient graph = new GraphServiceClient(new DelegateAuthenticationProvider( (requestMessage) => { AuthenticationResult result = null; var u = app.Users.FirstOrDefault(); // If a user has already signed-in, we try first to acquire the token silently, and then if this fails // we try to acquire it with a user interaction. if (u != null) { try { result = app.AcquireTokenSilentAsync(scopes, app.Users.FirstOrDefault()).Result; } catch (MsalClientException ex) { if (ex.ErrorCode == "interaction_required") { result = app.AcquireTokenAsync(scopes).Result; } } } else { result = app.AcquireTokenAsync(scopes).Result; } requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", result.AccessToken); return(Task.FromResult(0)); })); // Display the group Ids for all the group the signed-in user is part of. DisplayGroupIdsForGroupTheUserIsAMemberOf(graph).Wait(); // Display all the groups in the organization of the signed-in user DisplayGroupIdsForAllGroupsInMyOrg(graph).Wait(); // Display the group Ids for all the groups for a give user (here the signed-in user again) DisplayGroupIdsForUser(graph, graph.Me.Request().GetAsync().Result.UserPrincipalName).Wait(); }
public async Task TestAccountAcrossMultipleClientIdsAsync() { // Arrange var tokenCacheHelper = new TokenCacheHelper(); PublicClientApplication app = PublicClientApplicationBuilder.Create(MsalTestConstants.ClientId).BuildConcrete(); // Populate with tokens tied to ClientId2 tokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor, clientId: MsalTestConstants.ClientId2); app.UserTokenCacheInternal.Accessor.AssertItemCount( expectedAtCount: 2, expectedRtCount: 1, expectedAccountCount: 1, expectedIdtCount: 1, expectedAppMetadataCount: 1); // Act var accounts = await app.GetAccountsAsync().ConfigureAwait(false); // Assert Assert.IsFalse(accounts.Any(), "No accounts should be returned because the existing account to a different client"); // Arrange // Populate for clientid2 tokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor, clientId: MsalTestConstants.ClientId); app.UserTokenCacheInternal.Accessor.AssertItemCount( expectedAtCount: 4, expectedRtCount: 2, expectedAccountCount: 1, // still 1 account expectedIdtCount: 2, expectedAppMetadataCount: 2); // Act accounts = await app.GetAccountsAsync().ConfigureAwait(false); await app.RemoveAsync(accounts.Single()).ConfigureAwait(false); // Assert app.UserTokenCacheInternal.Accessor.AssertItemCount( expectedAtCount: 2, expectedRtCount: 1, expectedAccountCount: 0, expectedIdtCount: 1, expectedAppMetadataCount: 2); // app metadata is never deleted }
public void GetUsersTest() { PublicClientApplication app = new PublicClientApplication(TestConstants.DefaultClientId); IEnumerable <User> users = app.Users; Assert.IsNotNull(users); Assert.IsFalse(users.Any()); app.UserTokenCache = TokenCacheHelper.CreateCacheWithItems(); users = app.Users; Assert.IsNotNull(users); Assert.AreEqual(1, users.Count()); foreach (var user in users) { Assert.AreEqual(TestConstants.DefaultClientId, user.ClientId); Assert.IsNotNull(user.TokenCache); } // another cache entry for different home object id. user count should be 2. TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant, TestConstants.ScopeForAnotherResource, TestConstants.DefaultClientId, TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId + "more", TestConstants.DefaultPolicy); AuthenticationResultEx ex = new AuthenticationResultEx(); ex.Result = new AuthenticationResult("Bearer", key.ToString(), new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(3600))); ex.Result.User = new User { DisplayableId = TestConstants.DefaultDisplayableId, UniqueId = TestConstants.DefaultUniqueId, HomeObjectId = TestConstants.DefaultHomeObjectId }; ex.Result.ScopeSet = TestConstants.DefaultScope; ex.Result.FamilyId = "1"; ex.RefreshToken = "someRT"; app.UserTokenCache.tokenCacheDictionary[key] = ex; users = app.Users; Assert.IsNotNull(users); Assert.AreEqual(2, users.Count()); foreach (var user in users) { Assert.AreEqual(TestConstants.DefaultClientId, user.ClientId); Assert.IsNotNull(user.TokenCache); } }
public async Task ATS_NonExpired_NeedsRefresh_ValidResponse_Async() { // Arrange using (MockHttpAndServiceBundle harness = base.CreateTestHarness()) { Trace.WriteLine("1. Setup an app with a token cache with one AT"); PublicClientApplication app = SetupPca(harness); Trace.WriteLine("2. Configure AT so that it shows it needs to be refreshed"); UpdateATWithRefreshOn(app.UserTokenCacheInternal.Accessor, DateTime.UtcNow - TimeSpan.FromMinutes(1)); TokenCacheAccessRecorder cacheAccess = app.UserTokenCache.RecordAccess(); Trace.WriteLine("3. Configure AAD to respond with valid token to the refresh RT flow"); AddHttpMocks(TokenResponseType.Valid, harness.HttpManager, pca: true); // Act Trace.WriteLine("4. ATS - should perform an RT refresh"); var account = new Account(TestConstants.s_userIdentifier, TestConstants.DisplayableId, null); AuthenticationResult result = await app .AcquireTokenSilent( TestConstants.s_scope.ToArray(), account) .ExecuteAsync(CancellationToken.None) .ConfigureAwait(false); // Assert Assert.IsNotNull(result); Assert.AreEqual(0, harness.HttpManager.QueueSize, "MSAL should have refreshed the token because the original AT was marked for refresh"); cacheAccess.AssertAccessCounts(1, 1); MsalAccessTokenCacheItem ati = app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Single(); Assert.IsTrue(ati.RefreshOn > DateTime.UtcNow + TimeSpan.FromMinutes(10)); // New ATS does not refresh the AT because RefreshIn is in the future Trace.WriteLine("5. ATS - should fetch from the cache only"); result = await app .AcquireTokenSilent( TestConstants.s_scope.ToArray(), account) .ExecuteAsync(CancellationToken.None) .ConfigureAwait(false); Assert.IsNotNull(result); cacheAccess.AssertAccessCounts(2, 1); } }