-
Notifications
You must be signed in to change notification settings - Fork 228
fix: Clear persisted MSAL token cache on Disconnect-MgGraph #3649
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
gavinbarron
merged 9 commits into
main
from
gavinbarron/fix-disconnect-clear-token-cache
Jul 8, 2026
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
fcc8882
fix: Clear persisted MSAL token cache on Disconnect-MgGraph
gavinbarron 64974ff
Merge branch 'main' into gavinbarron/fix-disconnect-clear-token-cache
ramsessanchez 26063f4
Merge remote-tracking branch 'origin/main' into gavinbarron/fix-disco…
gavinbarron b54191c
feat: add -SignOutFromBroker switch to Disconnect-MgGraph for optiona…
gavinbarron 208ec40
feat: narrow broker cache clearing to the current session's account
gavinbarron cdc9d50
feat: narrow persisted file cache clearing to the current session's a…
gavinbarron 582d652
feat: add HomeAccountId to IAuthContext for session-scoped disconnect…
gavinbarron 491caff
docs: fill in -ProgressAction description for Disconnect-MgGraph
gavinbarron ad51fa5
test: update Disconnect-MgGraph parameter count for -SignOutFromBroker
gavinbarron File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
105 changes: 105 additions & 0 deletions
105
src/Authentication/Authentication.Core/Utilities/TokenCacheUtilities.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| // ------------------------------------------------------------------------------ | ||
| // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. | ||
| // ------------------------------------------------------------------------------ | ||
|
|
||
| using Microsoft.Identity.Client; | ||
| using Microsoft.Identity.Client.Extensions.Msal; | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.IO; | ||
| using System.Linq; | ||
| using System.Threading.Tasks; | ||
|
|
||
| namespace Microsoft.Graph.PowerShell.Authentication.Core.Utilities | ||
| { | ||
| /// <summary> | ||
| /// Utilities for managing the MSAL token cache persisted to disk by Azure.Identity. | ||
| /// </summary> | ||
| internal static class TokenCacheUtilities | ||
| { | ||
| // Azure.Identity internal constants for cache storage configuration. | ||
| // See: Azure/azure-sdk-for-net - sdk/core/Azure.Core/src/Identity/Constants.cs | ||
| private const string DefaultCacheKeychainService = "Microsoft.Developer.IdentityService"; | ||
| private const string DefaultCacheKeyringSchema = "msal.cache"; | ||
| private const string DefaultCacheKeyringCollection = "default"; | ||
| private static readonly KeyValuePair<string, string> DefaultCacheKeyringAttribute1 = | ||
| new KeyValuePair<string, string>("MsalClientID", "Microsoft.Developer.IdentityService"); | ||
| private static readonly KeyValuePair<string, string> DefaultCacheKeyringAttribute2 = | ||
| new KeyValuePair<string, string>("Microsoft.Developer.IdentityService", "1.0.0.0"); | ||
|
|
||
| // Azure.Identity appends CAE suffixes to the cache name internally. | ||
| private const string CaeEnabledSuffix = ".cae"; | ||
| private const string CaeDisabledSuffix = ".nocae"; | ||
|
|
||
| private static readonly string DefaultCacheDirectory = | ||
| Path.Combine( | ||
| Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), | ||
| ".IdentityService"); | ||
|
|
||
| /// <summary> | ||
| /// Clears the persisted MSAL token cache files created by Azure.Identity | ||
| /// for the given cache name. Clears both CAE-enabled and CAE-disabled variants. | ||
| /// When <paramref name="homeAccountId"/> identifies the current session's account, only that | ||
| /// account is removed from the cache; otherwise the entire cache is cleared as a fallback. | ||
| /// </summary> | ||
| /// <param name="cacheName">The cache name (e.g., "mg.msal.cache").</param> | ||
| /// <param name="clientId">The module's client id, used to enumerate cached accounts.</param> | ||
| /// <param name="authority">The authority URL used to build the public client application.</param> | ||
| /// <param name="homeAccountId"> | ||
| /// The HomeAccountId of the current session's account. When <c>null</c> or empty, or when no | ||
| /// matching account is found, the entire cache is cleared. | ||
| /// </param> | ||
| public static async Task ClearPersistedTokenCacheAsync(string cacheName, string clientId = null, string authority = null, string homeAccountId = null) | ||
| { | ||
| // Azure.Identity creates separate caches for CAE-enabled and CAE-disabled tokens. | ||
| await ClearCacheAsync(cacheName + CaeEnabledSuffix, clientId, authority, homeAccountId).ConfigureAwait(false); | ||
| await ClearCacheAsync(cacheName + CaeDisabledSuffix, clientId, authority, homeAccountId).ConfigureAwait(false); | ||
| } | ||
|
|
||
| private static async Task ClearCacheAsync(string cacheFileName, string clientId, string authority, string homeAccountId) | ||
| { | ||
| var storageProperties = new StorageCreationPropertiesBuilder(cacheFileName, DefaultCacheDirectory) | ||
| .WithMacKeyChain(DefaultCacheKeychainService, cacheFileName) | ||
| .WithLinuxKeyring( | ||
| DefaultCacheKeyringSchema, | ||
| DefaultCacheKeyringCollection, | ||
| cacheFileName, | ||
| DefaultCacheKeyringAttribute1, | ||
| DefaultCacheKeyringAttribute2) | ||
| .Build(); | ||
|
|
||
| var cacheHelper = await MsalCacheHelper.CreateAsync(storageProperties).ConfigureAwait(false); | ||
|
|
||
| // When the current session's account can be identified, remove only that account from the | ||
| // persisted cache so other accounts the user has signed into this module remain intact. | ||
| if (!string.IsNullOrEmpty(homeAccountId) && !string.IsNullOrEmpty(clientId)) | ||
| { | ||
| var builder = PublicClientApplicationBuilder.Create(clientId); | ||
| if (!string.IsNullOrEmpty(authority)) | ||
| { | ||
| builder = builder.WithAuthority(authority); | ||
| } | ||
| var pca = builder.Build(); | ||
| cacheHelper.RegisterCache(pca.UserTokenCache); | ||
|
|
||
| var accounts = await pca.GetAccountsAsync().ConfigureAwait(false); | ||
| var matchingAccounts = accounts | ||
| .Where(a => string.Equals(a.HomeAccountId?.Identifier, homeAccountId, StringComparison.OrdinalIgnoreCase)) | ||
| .ToList(); | ||
| if (matchingAccounts.Count > 0) | ||
| { | ||
| foreach (var account in matchingAccounts) | ||
| { | ||
| await pca.RemoveAsync(account).ConfigureAwait(false); | ||
| } | ||
| return; | ||
| } | ||
| } | ||
|
|
||
| // Fallback: no identifiable session account, clear the entire cache. | ||
| #pragma warning disable CS0618 // MsalCacheHelper.Clear is obsolete but is the correct approach for full cache wipe on disconnect | ||
| cacheHelper.Clear(); | ||
|
gavinbarron marked this conversation as resolved.
|
||
| #pragma warning restore CS0618 | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.