Skip to content

Fix that RemoveUser doesn't work when create Public Client with broker #27448

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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: 11 additions & 12 deletions src/Accounts/Accounts/Account/DisconnectAzureRmAccount.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,21 +124,20 @@ 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)
{
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)
{
if (GetContextModificationScope() == ContextModificationScope.CurrentUser)
{
AzureSession.Instance.AuthenticationFactory.RemoveUser(azureAccount, context.Environment.ActiveDirectoryAuthority);
}
profileClient.TryRemoveContext(context);
}
});
}

WriteObject(new PSAzureRmAccount(azureAccount));
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);
}

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

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

}

AzureSession.Instance.RaiseContextClearedEvent();
Expand Down
1 change: 1 addition & 0 deletions src/Accounts/Accounts/Context/GetAzureRMContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ 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();
}
}
Expand Down
11 changes: 5 additions & 6 deletions src/Accounts/Accounts/Context/RemoveAzureRmContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,16 @@
// 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 Microsoft.WindowsAzure.Commands.Utilities.Common;

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

namespace Microsoft.Azure.Commands.Profile.Context
{
Expand Down Expand Up @@ -91,7 +90,7 @@ public override void ExecuteCmdlet()
}
else
{
if (!tokenCacheProvider.TryRemoveAccount(removedContext.Account.Id))
if (!tokenCacheProvider.TryRemoveAccount(removedContext.Account.Id, removedContext.Environment.ActiveDirectoryAuthority))
{
WriteWarning(string.Format(Resources.NoContextsRemain, removedContext.Account.Id));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -822,8 +822,9 @@ public void RefreshContextsFromCache()
string authority = null;
if (TryGetEnvironment(AzureSession.Instance.GetProperty(AzureSession.Property.Environment), out IAzureEnvironment sessionEnvironment))
{
authority = $"{sessionEnvironment.ActiveDirectoryAuthority}organizations";
authority = $"{sessionEnvironment.ActiveDirectoryAuthority}/organizations";
}
//fixme, if Connect-AzAccount not run, when to get authority
var accounts = tokenCacheProvider.ListAccounts(authority);
if (!accounts.Any())
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

using Azure.Identity;

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

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

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

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

using Azure.Identity;

using Hyak.Common;

using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
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 +51,14 @@ public virtual void FlushTokenData()
_tokenCacheDataToFlush = null;
}

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

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

return CreatePublicClient(authority: authority)
return CreatePublicClient(authority)
.GetAccountsAsync()
.ConfigureAwait(false).GetAwaiter().GetResult();
}
Expand Down Expand Up @@ -192,18 +190,7 @@ public virtual IPublicClientApplication CreatePublicClient(string authority, str
/// </summary>
public virtual IPublicClientApplication CreatePublicClient(string authority = null)
{
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;
return CreatePublicClient(authority, organizationTenant);
}

public abstract TokenCachePersistenceOptions GetTokenCachePersistenceOptions();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,14 @@
// 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 @@ -103,9 +104,9 @@ protected override void RegisterCache(IPublicClientApplication client)
}
}

public override void ClearCache()
public override void ClearCache(string authority)
{
var client = CreatePublicClient();
var client = CreatePublicClient(authority);
var accounts = client.GetAccountsAsync().GetAwaiter().GetResult();
foreach (var account in accounts)
{
Expand Down
52 changes: 46 additions & 6 deletions src/Accounts/Authentication/Factories/AuthenticationFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,18 @@
// ----------------------------------------------------------------------------------

using Hyak.Common;

using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.Common.Authentication.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Properties;
using Microsoft.Azure.Commands.Common.Authentication.Utilities;
using Microsoft.Azure.Commands.Common.Exceptions;
using Microsoft.Azure.Commands.ResourceManager.Common;
using Microsoft.Azure.Commands.Shared.Config;
using Microsoft.Azure.PowerShell.Common.Config;
using Microsoft.Identity.Client;
using Microsoft.Rest;
using Microsoft.WindowsAzure.Commands.Common;

using System;
using System.Diagnostics;
using System.Linq;
using System.Security;
using System.Threading.Tasks;
Expand Down Expand Up @@ -449,6 +448,47 @@ public void RemoveUser(IAzureAccount account, IAzureTokenCache tokenCache)
}
}

/// <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="authority">The Microsoft Entra authority</param>
public void RemoveUser(IAzureAccount account, string authority)
{
if (account != null && !string.IsNullOrEmpty(account.Id) && !string.IsNullOrWhiteSpace(account.Type))
{
switch (account.Type)
{
case AzureAccount.AccountType.AccessToken:
account.SetProperty(AzureAccount.Property.AccessToken, null);
account.SetProperty(AzureAccount.Property.GraphAccessToken, null);
account.SetProperty(AzureAccount.Property.KeyVaultAccessToken, null);
break;
case AzureAccount.AccountType.ManagedService:
account.SetProperty(AzureAccount.Property.MSILoginUri, null);
break;
case AzureAccount.AccountType.ServicePrincipal:
try
{
KeyStore.RemoveSecureString(new ServicePrincipalKey(AzureAccount.Property.ServicePrincipalSecret,
account.Id, account.GetTenants().FirstOrDefault()));
KeyStore.RemoveSecureString(new ServicePrincipalKey(AzureAccount.Property.CertificatePassword,
account.Id, account.GetTenants().FirstOrDefault()));
}
catch
{
// make best effort to remove credentials
}

RemoveFromTokenCache(account, authority);
break;
case AzureAccount.AccountType.User:
RemoveFromTokenCache(account, authority);
break;
}
}
}

private string GetResourceId(string resourceIdorEndpointName, IAzureEnvironment environment)
{
return environment.GetEndpoint(resourceIdorEndpointName) ?? resourceIdorEndpointName;
Expand Down Expand Up @@ -485,20 +525,20 @@ private string GetEndpointToken(IAzureAccount account, string targetEndpoint)
return account.GetProperty(tokenKey);
}

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

var publicClient = tokenCacheProvider.CreatePublicClient();
var publicClient = tokenCacheProvider.CreatePublicClient(authority);
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
5 changes: 5 additions & 0 deletions tools/TestFx/Mocks/MockCertificateAuthenticationFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,5 +102,10 @@ public void RemoveUser(IAzureAccount account, IAzureTokenCache tokenCache)
{
throw new NotImplementedException();
}

public void RemoveUser(IAzureAccount account, string authority)
{
throw new NotImplementedException();
}
}
}
5 changes: 5 additions & 0 deletions tools/TestFx/Mocks/MockTokenAuthenticationFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,5 +125,10 @@ public void RemoveUser(IAzureAccount account, IAzureTokenCache tokenCache)
{
throw new NotImplementedException();
}

public void RemoveUser(IAzureAccount account, string authority)
{
throw new NotImplementedException();
}
}
}
Loading