Skip to content

Revert "Fix that RemoveUser doesn't work when create Public Client with broker" #27713

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
merged 1 commit into from
May 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 12 additions & 11 deletions src/Accounts/Accounts/Account/DisconnectAzureRmAccount.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,20 +124,21 @@ public override void ExecuteCmdlet()

if (ShouldProcess(string.Format("Log out principal '{0}'", azureAccount.Id), "log out"))
{
if (GetContextModificationScope() == ContextModificationScope.CurrentUser)
{
AzureSession.Instance.AuthenticationFactory.RemoveUser(azureAccount, null);
}

if (AzureRmProfileProvider.Instance.Profile != null)
{
ModifyContext((localProfile, profileClient) =>
{
var matchingContexts = localProfile.Contexts?.Values?.Where((c) => c != null && c.Account != null && string.Equals(c.Account.Id, azureAccount.Id, StringComparison.CurrentCultureIgnoreCase));
foreach (var context in matchingContexts)
{
if (GetContextModificationScope() == ContextModificationScope.CurrentUser)
{
AzureSession.Instance.AuthenticationFactory.RemoveUser(azureAccount, context.Environment);
}
profileClient.TryRemoveContext(context);
}
});
{
var matchingContexts = localProfile.Contexts?.Values?.Where((c) => c != null && c.Account != null && string.Equals(c.Account.Id, azureAccount.Id, StringComparison.CurrentCultureIgnoreCase));
foreach (var context in matchingContexts)
{
profileClient.TryRemoveContext(context);
}
});
}

WriteObject(new PSAzureRmAccount(azureAccount));
Expand Down
1 change: 0 additions & 1 deletion src/Accounts/Accounts/ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
-->

## Upcoming Release
* Fixed that removeUser didn't work when create Public Client with broker.

## Version 4.2.0
* Updated warning message about MFA. For more details, see https://go.microsoft.com/fwlink/?linkid=2276314
Expand Down
20 changes: 10 additions & 10 deletions src/Accounts/Accounts/Context/ClearAzureRmContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,29 +65,29 @@ void ClearContext(AzureRmProfile profile, RMProfileClient client)
bool result = false;
if (profile != null)
{
PowerShellTokenCacheProvider tokenCacheProvider = null;
if (!AzureSession.Instance.TryGetComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, out tokenCacheProvider))
{
WriteWarning(Resources.ClientFactoryNotRegisteredClear);
}

var contexts = profile.Contexts.Values;
foreach (var context in contexts)
{
tokenCacheProvider?.ClearCache(context.Environment.ActiveDirectoryAuthority);
client.TryRemoveContext(context);
}

if (tokenCacheProvider != null)
PowerShellTokenCacheProvider tokenCacheProvider;
if (!AzureSession.Instance.TryGetComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, out tokenCacheProvider))
{
profile.TrySetDefaultContext(new AzureContext());
WriteWarning(Resources.ClientFactoryNotRegisteredClear);
}
else
{
tokenCacheProvider.ClearCache();
var defaultContext = new AzureContext();
profile.TrySetDefaultContext(defaultContext);
result = true;
}

if (AzureSession.Instance.TryGetComponent(AzKeyStore.Name, out AzKeyStore keyStore))
{
keyStore?.Clear();
}

}

AzureSession.Instance.RaiseContextClearedEvent();
Expand Down
1 change: 0 additions & 1 deletion src/Accounts/Accounts/Context/GetAzureRMContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@ public override void ExecuteCmdlet()
var defaultProfile = DefaultProfile as AzureRmProfile;
if (defaultProfile != null && string.Equals(AzureSession.Instance?.ARMContextSaveMode, "CurrentUser"))
{
AzureSession.Instance.SetProperty(AzureSession.Property.Environment, DefaultContext.Environment.Name);
defaultProfile.RefreshContextsFromCache(_cmdletContext);
}
}
Expand Down
11 changes: 6 additions & 5 deletions src/Accounts/Accounts/Context/RemoveAzureRmContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,17 @@
// limitations under the License.
// ----------------------------------------------------------------------------------

using System;
using System.Linq;
using System.Management.Automation;

using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.Azure.Commands.Profile.Common;
using Microsoft.Azure.Commands.Profile.Models.Core;
using Microsoft.Azure.Commands.Profile.Properties;

using System;
using System.Linq;
using System.Management.Automation;
using Microsoft.WindowsAzure.Commands.Utilities.Common;

namespace Microsoft.Azure.Commands.Profile.Context
{
Expand Down Expand Up @@ -90,7 +91,7 @@ public override void ExecuteCmdlet()
}
else
{
if (!tokenCacheProvider.TryRemoveAccount(removedContext.Account.Id, removedContext.Environment.ActiveDirectoryAuthority))
if (!tokenCacheProvider.TryRemoveAccount(removedContext.Account.Id))
{
WriteWarning(string.Format(Resources.NoContextsRemain, removedContext.Account.Id));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -819,12 +819,9 @@ public void RefreshContextsFromCache(ICmdletContext cmdletContext)
out PowerShellTokenCacheProvider tokenCacheProvider);

string authority = null;
//If the function is called from "public virtual IAzureContext DefaultContext", authroity is empty and then ListAccounts will return empty.
//But as "ShouldRefreshContextsFromCache" is always false, the only call path is from GetAzureRMContext for now.
if (TryGetEnvironment(AzureSession.Instance.GetProperty(AzureSession.Property.Environment), out IAzureEnvironment sessionEnvironment))
{
authority = new Uri(new Uri(sessionEnvironment.ActiveDirectoryAuthority), "organizations").AbsoluteUri;

authority = $"{sessionEnvironment.ActiveDirectoryAuthority}organizations";
}
var accounts = tokenCacheProvider.ListAccounts(authority);
if (!accounts.Any())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

using Azure.Identity;

using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Identity.Client;

namespace Microsoft.Azure.Commands.Common.Authentication
Expand Down Expand Up @@ -47,7 +46,7 @@ public override void FlushTokenData()
}
}

public override void ClearCache(string authority)
public override void ClearCache()
{
InMemoryTokenCacheOptions = new InMemoryTokenCacheOptions();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@
// limitations under the License.
// ----------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;

using Azure.Identity;

using Hyak.Common;
Expand All @@ -20,15 +24,13 @@
using Microsoft.Azure.Commands.Common.Authentication.Abstractions.Extensions;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions.Interfaces;
using Microsoft.Azure.Commands.Common.Authentication.Utilities;
using Microsoft.Azure.Commands.Shared.Config;
using Microsoft.Azure.Internal.Subscriptions;
using Microsoft.Azure.Internal.Subscriptions.Models;
using Microsoft.Azure.PowerShell.Common.Config;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Broker;

using System;
using System.Collections.Generic;
using System.Linq;

namespace Microsoft.Azure.Commands.Common.Authentication
{
public abstract class PowerShellTokenCacheProvider
Expand All @@ -53,14 +55,14 @@ public virtual void FlushTokenData()
_tokenCacheDataToFlush = null;
}

public virtual void ClearCache(string authority = null)
public virtual void ClearCache()
{
}

public bool TryRemoveAccount(string accountId, string authority = null)
public bool TryRemoveAccount(string accountId)
{
TracingAdapter.Information(string.Format("[AuthenticationClientFactory] Calling GetAccountsAsync"));
var client = CreatePublicClient(authority);
var client = CreatePublicClient();
var account = client.GetAccountsAsync()
.ConfigureAwait(false).GetAwaiter().GetResult()
.FirstOrDefault(a => string.Equals(a.Username, accountId, StringComparison.OrdinalIgnoreCase));
Expand All @@ -87,7 +89,7 @@ public IEnumerable<IAccount> ListAccounts(string authority = null)
{
TracingAdapter.Information(string.Format("[PowerShellTokenCacheProvider] Calling GetAccountsAsync on {0}", authority ?? "AzureCloud"));

return CreatePublicClient(authority)
return CreatePublicClient(authority: authority)
.GetAccountsAsync()
.ConfigureAwait(false).GetAwaiter().GetResult();
}
Expand Down Expand Up @@ -193,7 +195,18 @@ public virtual IPublicClientApplication CreatePublicClient(string authority, str
/// </summary>
public virtual IPublicClientApplication CreatePublicClient(string authority = null)
{
return CreatePublicClient(authority, organizationTenant);
var builder = PublicClientApplicationBuilder.Create(Constants.PowerShellClientId);
if (AzConfigReader.IsWamEnabled(authority))
{
builder = builder.WithBroker(new BrokerOptions(BrokerOptions.OperatingSystems.Windows));
}
if (!string.IsNullOrEmpty(authority))
{
builder.WithAuthority(authority);
}
var client = builder.Build();
RegisterCache(client);
return client;
}

public abstract TokenCachePersistenceOptions GetTokenCachePersistenceOptions();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,13 @@
// limitations under the License.
// ----------------------------------------------------------------------------------

using System;

using Azure.Identity;

using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Extensions.Msal;

using System;

namespace Microsoft.Azure.Commands.Common.Authentication
{
public class SharedTokenCacheProvider : PowerShellTokenCacheProvider
Expand Down Expand Up @@ -104,9 +103,9 @@ protected override void RegisterCache(IPublicClientApplication client)
}
}

public override void ClearCache(string authority)
public override void ClearCache()
{
var client = CreatePublicClient(authority);
var client = CreatePublicClient();
var accounts = client.GetAccountsAsync().GetAwaiter().GetResult();
foreach (var account in accounts)
{
Expand Down
20 changes: 5 additions & 15 deletions src/Accounts/Authentication/Factories/AuthenticationFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -487,16 +487,6 @@ public ServiceClientCredentials GetServiceClientCredentials(string accessToken,
/// <param name="account"></param>
/// <param name="tokenCache">This parameter is no longer used. However to keep the API unchanged it's not removed.</param>
public void RemoveUser(IAzureAccount account, IAzureTokenCache tokenCache)
{
RemoveUser(account, environment: null);
}

/// <summary>
/// Remove any stored credentials for the given user and the Azure environment used.
/// </summary>
/// <param name="account">The account to remove credentials for</param>
/// <param name="environment">The environment which account belongs to</param>
public void RemoveUser(IAzureAccount account, IAzureEnvironment environment)
{
if (account != null && !string.IsNullOrEmpty(account.Id) && !string.IsNullOrWhiteSpace(account.Type))
{
Expand All @@ -523,10 +513,10 @@ public void RemoveUser(IAzureAccount account, IAzureEnvironment environment)
// make best effort to remove credentials
}

RemoveFromTokenCache(account, environment.ActiveDirectoryAuthority);
RemoveFromTokenCache(account);
break;
case AzureAccount.AccountType.User:
RemoveFromTokenCache(account, environment.ActiveDirectoryAuthority);
RemoveFromTokenCache(account);
break;
}
}
Expand Down Expand Up @@ -568,20 +558,20 @@ private string GetEndpointToken(IAzureAccount account, string targetEndpoint)
return account.GetProperty(tokenKey);
}

private void RemoveFromTokenCache(IAzureAccount account, string authority = null)
private void RemoveFromTokenCache(IAzureAccount account)
{
PowerShellTokenCacheProvider tokenCacheProvider;
if (!AzureSession.Instance.TryGetComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, out tokenCacheProvider))
{
throw new NullReferenceException(Resources.AuthenticationClientFactoryNotRegistered);
}

var publicClient = tokenCacheProvider.CreatePublicClient(authority);
var publicClient = tokenCacheProvider.CreatePublicClient();
var accounts = publicClient.GetAccountsAsync()
.ConfigureAwait(false).GetAwaiter().GetResult();
var tokenAccounts = accounts.Where(a => MatchCacheItem(account, a));
foreach (var tokenAccount in tokenAccounts)
{
{
publicClient.RemoveAsync(tokenAccount)
.ConfigureAwait(false).GetAwaiter().GetResult();
}
Expand Down
34 changes: 17 additions & 17 deletions tools/Common.Netcore.Dependencies.targets
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,22 @@
<ItemGroup>
<PackageReference Include="Microsoft.Rest.ClientRuntime" Version="2.3.24"/>
<PackageReference Include="Microsoft.Rest.ClientRuntime.Azure" Version="3.3.19"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Clients.Aks" Version="1.3.107-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Authentication.Abstractions" Version="1.3.107-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Clients.Authorization" Version="1.3.107-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Common" Version="1.3.107-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Clients.Compute" Version="1.3.107-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Clients.Graph.Rbac" Version="1.3.107-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Clients.KeyVault" Version="1.3.107-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Clients.Monitor" Version="1.3.107-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Clients.Network" Version="1.3.107-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Clients.PolicyInsights" Version="1.3.107-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Clients.ResourceManager" Version="1.3.107-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Storage" Version="1.3.107-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Clients.Storage.Management" Version="1.3.107-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Strategies" Version="1.3.107-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Clients.Websites" Version="1.3.107-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Common.Share" Version="1.3.107-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Clients.Aks" Version="1.3.106-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Authentication.Abstractions" Version="1.3.106-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Clients.Authorization" Version="1.3.106-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Common" Version="1.3.106-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Clients.Compute" Version="1.3.106-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Clients.Graph.Rbac" Version="1.3.106-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Clients.KeyVault" Version="1.3.106-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Clients.Monitor" Version="1.3.106-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Clients.Network" Version="1.3.106-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Clients.PolicyInsights" Version="1.3.106-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Clients.ResourceManager" Version="1.3.106-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Storage" Version="1.3.106-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Clients.Storage.Management" Version="1.3.106-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Strategies" Version="1.3.106-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Clients.Websites" Version="1.3.106-preview"/>
<PackageReference Include="Microsoft.Azure.PowerShell.Common.Share" Version="1.3.106-preview"/>
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
</ItemGroup>
<ItemGroup>
Expand All @@ -37,7 +37,7 @@
<PackageReference Include="PowerShellStandard.Library" Version="5.1.0" PrivateAssets="All" />
</ItemGroup>
<PropertyGroup>
<StorageToolsPath>$(NugetPackageRoot)\microsoft.azure.powershell.storage\1.3.107-preview\tools\</StorageToolsPath>
<StorageToolsPath>$(NugetPackageRoot)\microsoft.azure.powershell.storage\1.3.106-preview\tools\</StorageToolsPath>
</PropertyGroup>
<ItemGroup Condition="'$(OmitJsonPackage)' != 'true'">
<PackageReference Include="Newtonsoft.Json" Version="13.0.2"/>
Expand Down
5 changes: 0 additions & 5 deletions tools/TestFx/Mocks/MockCertificateAuthenticationFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,10 +124,5 @@ public IAccessToken Authenticate(IAzureAccount account, IAzureEnvironment enviro
{
throw new NotImplementedException();
}

public void RemoveUser(IAzureAccount account, IAzureEnvironment environment)
{
throw new NotImplementedException();
}
}
}
5 changes: 0 additions & 5 deletions tools/TestFx/Mocks/MockTokenAuthenticationFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -148,10 +148,5 @@ public ServiceClientCredentials GetServiceClientCredentials(IAzureContext contex
{
return GetServiceClientCredentials(context, targetEndpoint, AzureCmdletContext.CmdletNone);
}

public void RemoveUser(IAzureAccount account, IAzureEnvironment environment)
{
throw new NotImplementedException();
}
}
}
Loading