-
Notifications
You must be signed in to change notification settings - Fork 230
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
+485
−11
Merged
Changes from 1 commit
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
67 changes: 67 additions & 0 deletions
67
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,67 @@ | ||
| // ------------------------------------------------------------------------------ | ||
| // 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.Extensions.Msal; | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.IO; | ||
| 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. | ||
| /// </summary> | ||
| /// <param name="cacheName">The cache name (e.g., "mg.msal.cache").</param> | ||
| public static async Task ClearPersistedTokenCacheAsync(string cacheName) | ||
| { | ||
| // Azure.Identity creates separate caches for CAE-enabled and CAE-disabled tokens. | ||
| await ClearCacheAsync(cacheName + CaeEnabledSuffix).ConfigureAwait(false); | ||
| await ClearCacheAsync(cacheName + CaeDisabledSuffix).ConfigureAwait(false); | ||
| } | ||
|
|
||
| private static async Task ClearCacheAsync(string cacheFileName) | ||
| { | ||
| var storageProperties = new StorageCreationPropertiesBuilder(cacheFileName, DefaultCacheDirectory) | ||
| .WithMacKeyChain(DefaultCacheKeychainService, cacheFileName) | ||
| .WithLinuxKeyring( | ||
| DefaultCacheKeyringSchema, | ||
| DefaultCacheKeyringCollection, | ||
| cacheFileName, | ||
| DefaultCacheKeyringAttribute1, | ||
| DefaultCacheKeyringAttribute2) | ||
| .Build(); | ||
|
|
||
| var cacheHelper = await MsalCacheHelper.CreateAsync(storageProperties).ConfigureAwait(false); | ||
| #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 | ||
| } | ||
| } | ||
| } | ||
80 changes: 80 additions & 0 deletions
80
src/Authentication/Authentication.Test/TokenCache/TokenCacheUtilitiesTests.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,80 @@ | ||
| using Microsoft.Graph.PowerShell.Authentication; | ||
| using Microsoft.Graph.PowerShell.Authentication.Core.TokenCache; | ||
| using Microsoft.Graph.PowerShell.Authentication.Core.Utilities; | ||
| using System; | ||
| using System.IO; | ||
| using System.Text; | ||
| using System.Threading.Tasks; | ||
| using Xunit; | ||
|
|
||
| namespace Microsoft.Graph.Authentication.Test.TokenCache | ||
| { | ||
| public class TokenCacheUtilitiesTests : IDisposable | ||
| { | ||
| public TokenCacheUtilitiesTests() | ||
| { | ||
| GraphSession.Initialize(() => new GraphSession()); | ||
| GraphSession.Instance.InMemoryTokenCache = new InMemoryTokenCache(); | ||
| } | ||
|
|
||
| public void Dispose() | ||
| { | ||
| GraphSession.Reset(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task LogoutAsyncShouldClearInMemoryCacheForProcessScope() | ||
| { | ||
| // Arrange | ||
| GraphSession.Instance.InMemoryTokenCache = new InMemoryTokenCache( | ||
| Encoding.UTF8.GetBytes("mockTokenData")); | ||
| GraphSession.Instance.AuthContext = new AuthContext | ||
| { | ||
| AuthType = AuthenticationType.UserProvidedAccessToken, | ||
| ContextScope = ContextScope.Process | ||
| }; | ||
|
|
||
| // Act | ||
| var result = await AuthenticationHelpers.LogoutAsync(); | ||
|
|
||
| // Assert | ||
| Assert.NotNull(result); | ||
| Assert.Equal(AuthenticationType.UserProvidedAccessToken, result.AuthType); | ||
| Assert.Null(GraphSession.Instance.AuthContext); | ||
| Assert.Null(GraphSession.Instance.GraphHttpClient); | ||
| Assert.Empty(GraphSession.Instance.InMemoryTokenCache.ReadTokenData()); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task LogoutAsyncShouldNotThrowWhenAuthContextIsNull() | ||
| { | ||
| // Arrange | ||
| GraphSession.Instance.AuthContext = null; | ||
|
|
||
| // Act - should not throw even though there's no auth context | ||
| var result = await AuthenticationHelpers.LogoutAsync(); | ||
|
|
||
| // Assert | ||
| Assert.Null(result); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task LogoutAsyncShouldAttemptCacheClearForCurrentUserScope() | ||
| { | ||
| // Arrange | ||
| GraphSession.Instance.AuthContext = new AuthContext | ||
| { | ||
| AuthType = AuthenticationType.UserProvidedAccessToken, | ||
| ContextScope = ContextScope.CurrentUser | ||
| }; | ||
|
|
||
| // Act - should not throw even if no persisted cache exists on disk | ||
| var result = await AuthenticationHelpers.LogoutAsync(); | ||
|
|
||
| // Assert | ||
| Assert.NotNull(result); | ||
| Assert.Equal(ContextScope.CurrentUser, result.ContextScope); | ||
| Assert.Null(GraphSession.Instance.AuthContext); | ||
| } | ||
| } | ||
| } |
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 |
|---|---|---|
| @@ -1 +1 @@ | ||
| Use Disconnect-MgGraph to sign out. | ||
| Use Disconnect-MgGraph to sign out. This clears the persisted MSAL token cache from disk when using CurrentUser context scope, as well as removing the in-memory token cache and authentication record. |
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
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.