Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
1 change: 1 addition & 0 deletions src/Accounts/Accounts/Account/ConnectAzureRmAccount.cs
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,7 @@ public override void ExecuteCmdlet()
}

profileClient.WarningLog = (message) => _tasks.Enqueue(new Task(() => this.WriteWarning(message)));
profileClient.DebugLog = (message) => _tasks.Enqueue(new Task(() => this.WriteDebugWithTimestamp(message)));
var task = new Task<AzureRmProfile>( () => profileClient.Login(
azureAccount,
_environment,
Expand Down
28 changes: 21 additions & 7 deletions src/Accounts/Accounts/Models/RMProfileClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ public class RMProfileClient
private IProfileOperations _profile;
private IAzureTokenCache _cache;
public Action<string> WarningLog;
public Action<string> DebugLog;

private IAzureContext DefaultContext
{
Expand Down Expand Up @@ -242,9 +243,10 @@ public AzureRmProfile Login(
token = null;
}
}
catch
catch(Exception e)
{
WriteWarningMessage(string.Format(ProfileMessages.UnableToAqcuireToken, tenant));
WriteWarningMessage(string.Format(ProfileMessages.UnableToAqcuireToken, tenant, e.Message));
WriteDebugMessage(string.Format(ProfileMessages.UnableToAqcuireToken, tenant, e.ToString()));
}

if (token != null &&
Expand Down Expand Up @@ -498,12 +500,13 @@ public IEnumerable<IAzureSubscription> ListSubscriptions(string tenantIdOrDomain
ListAllSubscriptionsForTenant(
(tenant.GetId() == Guid.Empty) ? tenant.Directory : tenant.Id.ToString()));
}
catch (AadAuthenticationException)
catch (AadAuthenticationException e)
{
WriteWarningMessage(string.Format(
ProfileMessages.UnableToLogin,
_profile.DefaultContext.Account,
tenant));
WriteDebugMessage(e.ToString());
}

}
Expand Down Expand Up @@ -604,6 +607,7 @@ private bool TryGetTenantSubscription(IAccessToken accessToken,
if (isTenantPresent || !string.Equals(ex.Body?.Code, "InvalidAuthenticationTokenTenant", StringComparison.OrdinalIgnoreCase))
{
WriteWarningMessage(ex.Message);
WriteDebugMessage(ex.ToString());
}
}

Expand Down Expand Up @@ -652,9 +656,10 @@ private List<AzureTenant> ListAccountTenants(

result = SubscriptionAndTenantClient?.ListAccountTenants(commonTenantToken, environment);
}
catch
catch(Exception e)
{
WriteWarningMessage(string.Format(ProfileMessages.UnableToAqcuireToken, commonTenant));
WriteWarningMessage(string.Format(ProfileMessages.UnableToAqcuireToken, commonTenant, e.Message));
WriteDebugMessage(string.Format(ProfileMessages.UnableToAqcuireToken, commonTenant, e.ToString()));
if (account.IsPropertySet(AzureAccount.Property.Tenants))
{
result =
Expand Down Expand Up @@ -698,9 +703,10 @@ private IEnumerable<AzureSubscription> ListAllSubscriptionsForTenant(
{
accessToken = AcquireAccessToken(account, environment, tenantId, password, promptBehavior, null);
}
catch
catch(Exception e)
{
WriteWarningMessage(string.Format(ProfileMessages.UnableToAqcuireToken, tenantId));
WriteWarningMessage(string.Format(ProfileMessages.UnableToAqcuireToken, tenantId, e.Message));
WriteDebugMessage(string.Format(ProfileMessages.UnableToAqcuireToken, tenantId, e.ToString()));
return new List<AzureSubscription>();
}

Expand All @@ -715,6 +721,14 @@ private void WriteWarningMessage(string message)
}
}

private void WriteDebugMessage(string message)
{
if(DebugLog != null)
{
DebugLog(message);
}
}

public ISubscriptionClientWrapper SubscriptionAndTenantClient = null;
}
}
2 changes: 1 addition & 1 deletion src/Accounts/Accounts/Properties/Resources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/Accounts/Accounts/Properties/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@
<value>To create an access token credential, you must provide an access token account.</value>
</data>
<data name="UnableToAqcuireToken" xml:space="preserve">
<value>Unable to acquire token for tenant '{0}'</value>
<value>Unable to acquire token for tenant '{0}' with error '{1}'</value>
</data>
<data name="UnableToLogin" xml:space="preserve">
<value>Could not authenticate user account '{0}' with tenant '{1}'. Subscriptions in this tenant will not be listed. Please login again using Connect-AzAccount to view the subscriptions in this tenant.</value>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class MockMsalAccessTokenAcquirer : MsalAccessTokenAcquirer

public TokenRequestContext TokenRequestContext { get; set; }

internal override async Task<IAccessToken> GetAccessTokenAsync(TokenCredential tokenCredential, TokenRequestContext requestContext, CancellationToken cancellationToken, string tenantId = null, string userId = null, string homeAccountId = "")
internal override async Task<IAccessToken> GetAccessTokenAsync(string callerClassName, string parametersLog, TokenCredential tokenCredential, TokenRequestContext requestContext, CancellationToken cancellationToken, string tenantId = null, string userId = null, string homeAccountId = "")
{
TokenCredential = tokenCredential;
TokenRequestContext = requestContext;
Expand Down
6 changes: 3 additions & 3 deletions src/Accounts/Authenticators/AccessTokenAuthenticator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public override Task<IAccessToken> Authenticate(AuthenticationParameters paramet
resourceId.EqualsInsensitively(environment.GetEndpoint(AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId)))
&& account.IsPropertySet(AzureAccount.Property.KeyVaultAccessToken))
{
TracingAdapter.Information(string.Format("[AccessTokenAuthenticator] Creating KeyVault access token - Tenant: '{0}', ResourceId: '{1}', UserId: '{2}'", tenant, resourceId, account.Id));
TracingAdapter.Information($"{DateTime.Now:T} - [AccessTokenAuthenticator] Creating KeyVault access token - Tenant: '{tenant}', ResourceId: '{resourceId}', UserId: '{account.Id}'");
rawToken.AccessToken = account.GetProperty(AzureAccount.Property.KeyVaultAccessToken);
}
else if ((resourceId.EqualsInsensitively(environment.GraphEndpointResourceId) ||
Expand All @@ -55,7 +55,7 @@ public override Task<IAccessToken> Authenticate(AuthenticationParameters paramet
resourceId.EqualsInsensitively(environment.GetEndpoint(AzureEnvironment.Endpoint.GraphEndpointResourceId)))
&& account.IsPropertySet(AzureAccount.Property.GraphAccessToken))
{
TracingAdapter.Information(string.Format("[AccessTokenAuthenticator] Creating Graph access token - Tenant: '{0}', ResourceId: '{1}', UserId: '{2}'", tenant, resourceId, account.Id));
TracingAdapter.Information($"{DateTime.Now:T} - [AccessTokenAuthenticator] Creating Graph access token - Tenant: '{tenant}', ResourceId: '{resourceId}', UserId: '{account.Id}'");
rawToken.AccessToken = account.GetProperty(AzureAccount.Property.GraphAccessToken);
}
else if ((resourceId.EqualsInsensitively(environment.ActiveDirectoryServiceEndpointResourceId) ||
Expand All @@ -64,7 +64,7 @@ public override Task<IAccessToken> Authenticate(AuthenticationParameters paramet
resourceId.EqualsInsensitively(environment.GetEndpoint(AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId)))
&& account.IsPropertySet(AzureAccount.Property.AccessToken))
{
TracingAdapter.Information(string.Format("[AccessTokenAuthenticator] Creating access token - Tenant: '{0}', ResourceId: '{1}', UserId: '{2}'", tenant, resourceId, account.Id));
TracingAdapter.Information($"{DateTime.Now:T} - [AccessTokenAuthenticator] Creating access token - Tenant: '{tenant}', ResourceId: '{resourceId}', UserId: '{account.Id}'");
rawToken.AccessToken = account.GetAccessToken();
}
else
Expand Down
3 changes: 3 additions & 0 deletions src/Accounts/Authenticators/DeviceCodeAuthenticator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
using Azure.Core;
using Azure.Identity;

using Hyak.Common;

using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.ResourceManager.Common;
Expand Down Expand Up @@ -53,6 +55,7 @@ public override Task<IAccessToken> Authenticate(AuthenticationParameters paramet
};
var codeCredential = new DeviceCodeCredential(options);

TracingAdapter.Information($"{DateTime.Now:T} - [DeviceCodeAuthenticator] Calling DeviceCodeCredential.AuthenticateAsync - TenantId:'{options.TenantId}', Scopes:'{string.Join(",", scopes)}', AuthorityHost:'{options.AuthorityHost}'");
var authTask = codeCredential.AuthenticateAsync(requestContext, cancellationToken);
return MsalAccessToken.GetAccessTokenAsync(
authTask,
Expand Down
5 changes: 5 additions & 0 deletions src/Accounts/Authenticators/InteractiveUserAuthenticator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
// ----------------------------------------------------------------------------------

using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;
Expand All @@ -21,6 +22,8 @@
using Azure.Core;
using Azure.Identity;

using Hyak.Common;

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

Expand Down Expand Up @@ -65,6 +68,8 @@ public override Task<IAccessToken> Authenticate(AuthenticationParameters paramet
RedirectUri = GetReplyUrl(onPremise, interactiveParameters),
};
var browserCredential = new InteractiveBrowserCredential(options);

TracingAdapter.Information($"{DateTime.Now:T} - [InteractiveUserAuthenticator] Calling InteractiveBrowserCredential.AuthenticateAsync with TenantId:'{options.TenantId}', Scopes:'{string.Join(",", scopes)}', AuthorityHost:'{options.AuthorityHost}', RedirectUri:'{options.RedirectUri}'");
var authTask = browserCredential.AuthenticateAsync(requestContext, cancellationToken);

return MsalAccessToken.GetAccessTokenAsync(
Expand Down
14 changes: 12 additions & 2 deletions src/Accounts/Authenticators/ManagedServiceIdentityAuthenticator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,16 @@
// limitations under the License.
// ----------------------------------------------------------------------------------

using System;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

using Azure.Core;
using Azure.Identity;

using Hyak.Common;

using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.PowerShell.Authenticators.Factories;
Expand Down Expand Up @@ -47,8 +50,15 @@ public override Task<IAccessToken> Authenticate(AuthenticationParameters paramet

var identityCredential = azureCredentialFactory.CreateManagedIdentityCredential(userAccountId);
var msalAccessTokenAcquirer = msalAccessTokenAcquirerFactory.CreateMsalAccessTokenAcquirer();
return msalAccessTokenAcquirer.GetAccessTokenAsync(identityCredential, requestContext, cancellationToken,
msiParameters.TenantId, msiParameters.Account.Id);
var parametersLog = $"- TenantId:'{msiParameters.TenantId}', Scopes:'{string.Join(",", scopes)}', UserId:'{userAccountId}'";
return msalAccessTokenAcquirer.GetAccessTokenAsync(
nameof(ManagedServiceIdentityAuthenticator),
parametersLog,
identityCredential,
requestContext,
cancellationToken,
msiParameters.TenantId,
msiParameters.Account.Id);
}

public override bool CanAuthenticate(AuthenticationParameters parameters)
Expand Down
6 changes: 6 additions & 0 deletions src/Accounts/Authenticators/MsalAccessToken.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
using Azure.Core;
using Azure.Identity;

using Hyak.Common;

using Microsoft.Azure.Commands.Common.Authentication;

namespace Microsoft.Azure.PowerShell.Authenticators
Expand Down Expand Up @@ -66,13 +68,16 @@ public void AuthorizeRequest(Action<string, string> authTokenSetter)
}

internal static async Task<IAccessToken> GetAccessTokenAsync(
string callerClassName,
string parametersLog,
TokenCredential tokenCredential,
TokenRequestContext requestContext,
CancellationToken cancellationToken,
string tenantId = null,
string userId = null,
string homeAccountId = "")
{
TracingAdapter.Information($"{DateTime.Now:T} - [{callerClassName}] Calling {tokenCredential.GetType().Name}.GetTokenAsync {parametersLog}");
var token = await tokenCredential.GetTokenAsync(requestContext, cancellationToken).ConfigureAwait(false);
return new MsalAccessToken(tokenCredential, requestContext, token.Token, token.ExpiresOn, tenantId, userId, homeAccountId);
}
Expand All @@ -86,6 +91,7 @@ internal static async Task<IAccessToken> GetAccessTokenAsync(
{
var record = await authTask.ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
TracingAdapter.Information($"{DateTime.Now:T} - [MsalAccessToken] Calling {tokenCredential.GetType().Name}.GetTokenAsync - Scopes:'{string.Join(",", requestContext.Scopes)}'");
var token = await tokenCredential.GetTokenAsync(requestContext, cancellationToken).ConfigureAwait(false);

return new MsalAccessToken(tokenCredential, requestContext, token.Token, token.ExpiresOn, record.TenantId, record.Username, record.HomeAccountId);
Expand Down
7 changes: 7 additions & 0 deletions src/Accounts/Authenticators/MsalAccessTokenAcquirer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,26 +12,32 @@
// limitations under the License.
// ----------------------------------------------------------------------------------

using System;
using System.Threading;
using System.Threading.Tasks;

using Azure.Core;
using Azure.Identity;

using Hyak.Common;

using Microsoft.Azure.Commands.Common.Authentication;

namespace Microsoft.Azure.PowerShell.Authenticators
{
public class MsalAccessTokenAcquirer
{
internal virtual async Task<IAccessToken> GetAccessTokenAsync(
string callerClassName,
string parametersLog,
TokenCredential tokenCredential,
TokenRequestContext requestContext,
CancellationToken cancellationToken,
string tenantId = null,
string userId = null,
string homeAccountId = "")
{
TracingAdapter.Information($"{DateTime.Now:T} - [{callerClassName}] Calling {tokenCredential.GetType().Name}.GetTokenAsync {parametersLog}");
var token = await tokenCredential.GetTokenAsync(requestContext, cancellationToken).ConfigureAwait(false);
return new MsalAccessToken(tokenCredential, requestContext, token.Token, token.ExpiresOn, tenantId, userId, homeAccountId);
}
Expand All @@ -44,6 +50,7 @@ internal virtual async Task<IAccessToken> GetAccessTokenAsync(
{
var record = await authTask.ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
TracingAdapter.Information($"{DateTime.Now:T} - [MsalAccessTokenAcquirer] Calling {tokenCredential.GetType().Name}.GetTokenAsync - Scopes:'{string.Join(",", requestContext.Scopes)}'");
var token = await tokenCredential.GetTokenAsync(requestContext, cancellationToken).ConfigureAwait(false);

return new MsalAccessToken(tokenCredential, requestContext, token.Token, token.ExpiresOn, record.TenantId, record.Username, record.HomeAccountId);
Expand Down
8 changes: 8 additions & 0 deletions src/Accounts/Authenticators/ServicePrincipalAuthenticator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
using Azure.Core;
using Azure.Identity;

using Hyak.Common;

using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Identity.Client;
Expand Down Expand Up @@ -55,7 +57,10 @@ public override Task<IAccessToken> Authenticate(AuthenticationParameters paramet
//Service Principal with Certificate
var certificate = AzureSession.Instance.DataStore.GetCertificate(spParameters.Thumbprint);
ClientCertificateCredential certCredential = new ClientCertificateCredential(tenantId, spParameters.ApplicationId, certificate, options);
var parametersLog = $"- Thumbprint:'{spParameters.Thumbprint}', ApplicationId:'{spParameters.ApplicationId}', TenantId:'{tenantId}', Scopes:'{string.Join(",", scopes)}', AuthorityHost:'{options.AuthorityHost}'";
return MsalAccessToken.GetAccessTokenAsync(
nameof(ServicePrincipalAuthenticator),
parametersLog,
certCredential,
requestContext,
cancellationToken,
Expand All @@ -66,7 +71,10 @@ public override Task<IAccessToken> Authenticate(AuthenticationParameters paramet
{
// service principal with secret
var secretCredential = new ClientSecretCredential(tenantId, spParameters.ApplicationId, spParameters.Secret.ConvertToString(), options);
var parametersLog = $"- ApplicationId:'{spParameters.ApplicationId}', TenantId:'{tenantId}', Scopes:'{string.Join(",", scopes)}', AuthorityHost:'{options.AuthorityHost}'";
return MsalAccessToken.GetAccessTokenAsync(
nameof(ServicePrincipalAuthenticator),
parametersLog,
secretCredential,
requestContext,
cancellationToken,
Expand Down
14 changes: 12 additions & 2 deletions src/Accounts/Authenticators/SilentAuthenticator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
using Azure.Core;
using Azure.Identity;

using Hyak.Common;

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

Expand Down Expand Up @@ -48,8 +50,16 @@ public override Task<IAccessToken> Authenticate(AuthenticationParameters paramet

var cacheCredential = new SharedTokenCacheCredential(options);
var requestContext = new TokenRequestContext(scopes);
var tokenTask = cacheCredential.GetTokenAsync(requestContext);
return MsalAccessToken.GetAccessTokenAsync(cacheCredential, requestContext, cancellationToken, silentParameters.TenantId, silentParameters.UserId, silentParameters.HomeAccountId);
var parametersLog = $"- TenantId:'{options.TenantId}', Scopes:'{string.Join(",", scopes)}', AuthorityHost:'{options.AuthorityHost}', UserId:'{silentParameters.UserId}'";
return MsalAccessToken.GetAccessTokenAsync(
nameof(SilentAuthenticator),
parametersLog,
cacheCredential,
requestContext,
cancellationToken,
silentParameters.TenantId,
silentParameters.UserId,
silentParameters.HomeAccountId);
}

public override bool CanAuthenticate(AuthenticationParameters parameters)
Expand Down
Loading