From f98103c75ae525a44e83311066430344c9a2687f Mon Sep 17 00:00:00 2001 From: "Erich(Renyong) Wang" Date: Mon, 2 Nov 2020 09:36:30 +0800 Subject: [PATCH 1/6] add cmdlet Get-AzAccessToken --- src/Accounts/Accounts/Az.Accounts.psd1 | 2 +- src/Accounts/Accounts/ChangeLog.md | 1 + .../Accounts/Properties/Resources.Designer.cs | 18 +++ .../Accounts/Properties/Resources.resx | 6 + .../Accounts/Token/GetAzureRmAccessToken.cs | 131 ++++++++++++++++++ src/Accounts/Accounts/help/Az.Accounts.md | 9 +- .../Accounts/help/Get-AzAccessToken.md | 99 +++++++++++++ 7 files changed, 259 insertions(+), 7 deletions(-) create mode 100644 src/Accounts/Accounts/Token/GetAzureRmAccessToken.cs create mode 100644 src/Accounts/Accounts/help/Get-AzAccessToken.md diff --git a/src/Accounts/Accounts/Az.Accounts.psd1 b/src/Accounts/Accounts/Az.Accounts.psd1 index 7d9b3f57f530..ce7b5ca2171b 100644 --- a/src/Accounts/Accounts/Az.Accounts.psd1 +++ b/src/Accounts/Accounts/Az.Accounts.psd1 @@ -106,7 +106,7 @@ CmdletsToExport = 'Disable-AzDataCollection', 'Disable-AzContextAutosave', 'Disconnect-AzAccount', 'Get-AzContextAutosaveSetting', 'Set-AzDefault', 'Get-AzDefault', 'Clear-AzDefault', 'Register-AzModule', 'Enable-AzureRmAlias', 'Disable-AzureRmAlias', - 'Uninstall-AzureRm', 'Invoke-AzRestMethod' + 'Uninstall-AzureRm', 'Invoke-AzRestMethod', 'Get-AzAccessToken' # Variables to export from this module # VariablesToExport = @() diff --git a/src/Accounts/Accounts/ChangeLog.md b/src/Accounts/Accounts/ChangeLog.md index a281b19be8db..1a3c426351ff 100644 --- a/src/Accounts/Accounts/ChangeLog.md +++ b/src/Accounts/Accounts/ChangeLog.md @@ -18,6 +18,7 @@ - Additional information about change #1 --> ## Upcoming Release +* Add new cmdlet `Get-AzAccessToken` * Supported interrupting login by hitting CTRL+C * Fixed an issue causing `Connect-AzAccount -KeyVaultAccessToken` not working [#13127] * Fixed null reference and method case insensitive in `Invoke-AzRestMethod` diff --git a/src/Accounts/Accounts/Properties/Resources.Designer.cs b/src/Accounts/Accounts/Properties/Resources.Designer.cs index 93dbc8ff3455..10c812f79269 100644 --- a/src/Accounts/Accounts/Properties/Resources.Designer.cs +++ b/src/Accounts/Accounts/Properties/Resources.Designer.cs @@ -591,6 +591,15 @@ internal static string InvalidEndpointProvided { } } + /// + /// Looks up a localized string similar to The specified ResourceTypeName "{0}" is not supported, please provide a valid value. e.g. Arm, AadGraph, etc.. + /// + internal static string InvalidResourceTypeName { + get { + return ResourceManager.GetString("InvalidResourceTypeName", resourceCulture); + } + } + /// /// Looks up a localized string similar to The provided subscription ID "{0}" is not a valid Guid.. /// @@ -600,6 +609,15 @@ internal static string InvalidSubscriptionId { } } + /// + /// Looks up a localized string similar to Could not find TenantId "{0}" in logged-in contexts. Please make sure you have logged into the tenant, e.g. Connect-AzAccount -Tenant xxx. + /// + internal static string InvalidTenantId { + get { + return ResourceManager.GetString("InvalidTenantId", resourceCulture); + } + } + /// /// Looks up a localized string similar to {0} account in environment '{1}'. /// diff --git a/src/Accounts/Accounts/Properties/Resources.resx b/src/Accounts/Accounts/Properties/Resources.resx index 2f6c32be4740..ba9e75094a41 100644 --- a/src/Accounts/Accounts/Properties/Resources.resx +++ b/src/Accounts/Accounts/Properties/Resources.resx @@ -519,4 +519,10 @@ Please run 'Connect-AzAccount -DeviceCode' if browser is not supported in this session. + + The specified ResourceTypeName "{0}" is not supported, please provide a valid value. e.g. Arm, AadGraph, etc. + + + Could not find TenantId "{0}" in logged-in contexts. Please make sure you have logged into the tenant, e.g. Connect-AzAccount -Tenant xxx + \ No newline at end of file diff --git a/src/Accounts/Accounts/Token/GetAzureRmAccessToken.cs b/src/Accounts/Accounts/Token/GetAzureRmAccessToken.cs new file mode 100644 index 000000000000..58b363a16fd6 --- /dev/null +++ b/src/Accounts/Accounts/Token/GetAzureRmAccessToken.cs @@ -0,0 +1,131 @@ +// ---------------------------------------------------------------------------------- +// +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; +using System.Net.Http; +using System.Threading; + +using Microsoft.Azure.Commands.Common.Authentication; +using Microsoft.Azure.Commands.Common.Authentication.Abstractions; +using Microsoft.Azure.Commands.Common.Authentication.Models; +using Microsoft.Azure.Commands.ResourceManager.Common; +using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; + +namespace Microsoft.Azure.Commands.Profile.Token +{ + [Cmdlet(VerbsCommon.Get, AzureRMConstants.AzureRMPrefix + "AccessToken")] + [OutputType(typeof(string))] + public class GetAzureRmAccessTokenCommand : AzureRMCmdlet + { + private const string AuthorizationHeaderName = "Authorization"; + private const string ResourceUriParameterSet = "ResourceUri"; + private const string KnownResourceNameParameterSet = "KnownResourceTypeName"; + + //TODO: Support ResourceUri directly + //[Parameter(ParameterSetName = ResourceUriParameterSet, Mandatory = false)] + //public string Resource { get; set; } + + [Parameter(ParameterSetName = KnownResourceNameParameterSet, + Mandatory = false, + HelpMessage = "Optional resouce type name, supported values: AadGraph, Analysis, Arm, Attest, DataLake, KeyVault, OperationInsights, Synapse. Default value is Arm if not specified.")] + [PSArgumentCompleter( + SupportedResourceNames.AadGraph, + SupportedResourceNames.Analysis, + SupportedResourceNames.Arm, + SupportedResourceNames.Attest, + SupportedResourceNames.DataLake, + SupportedResourceNames.KeyVault, + SupportedResourceNames.OperationInsights, + SupportedResourceNames.Synapse + )] + public string ResourceTypeName { get; set; } + + //Use tenant in default context if not specified + [Parameter(Mandatory = false, HelpMessage = "Optional Tenant Id. Use tenant id of default context if not specified.")] + public string TenantId { get; set; } + + public override void ExecuteCmdlet() + { + base.ExecuteCmdlet(); + + string resourceId = null; + + if (ResourceTypeName == null) + { + ResourceTypeName = SupportedResourceNames.Arm; + } + if (!SupportedResourceNames.ResourceNameMap.ContainsKey(ResourceTypeName)) + { + throw new ArgumentException(Properties.Resources.InvalidResourceTypeName.FormatInvariant(ResourceTypeName), nameof(ResourceTypeName)); + } + + resourceId = SupportedResourceNames.ResourceNameMap[ResourceTypeName]; + + resourceId = string.IsNullOrEmpty(resourceId) ? AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId : resourceId; + + IAzureContext context = DefaultContext; + if (!string.IsNullOrEmpty(TenantId) && !string.Equals(context.Tenant.Id, TenantId, StringComparison.OrdinalIgnoreCase)) + { + var profile = DefaultProfile as AzureRmProfile; + context = profile.Contexts.FirstOrDefault(c => + string.Equals(c.Value.Tenant.Id, TenantId, StringComparison.OrdinalIgnoreCase)).Value; + if (context == null) + { + throw new ArgumentException(Properties.Resources.InvalidTenantId.FormatInvariant(TenantId), nameof(TenantId)); + } + } + var credential = AzureSession.Instance.AuthenticationFactory.GetServiceClientCredentials( + context, + resourceId); + var requestMessage = new HttpRequestMessage(); + credential.ProcessHttpRequestAsync(requestMessage, default(CancellationToken)).ConfigureAwait(false).GetAwaiter().GetResult(); + if (requestMessage.Headers.Contains(AuthorizationHeaderName)) + { + var token = requestMessage.Headers.GetValues(AuthorizationHeaderName) + ?.FirstOrDefault()?.Substring("Bearer ".Length); + WriteObject(token); + } + } + + internal class SupportedResourceNames + { + //TODO: Support 'Batch' and 'ManagedHsm', need to upate AzureEnvironmentExtensions.GetTokenAudience() to support more endpoints + + public const string Arm = "Arm"; + public const string AadGraph = "AadGraph"; + public const string DataLake = "DataLake"; + public const string KeyVault = "KeyVault"; + + public const string Analysis = "Analysis"; + public const string Attest = "Attest"; + public const string OperationInsights = "OperationInsights"; + public const string Synapse = "Synapse"; + + internal static Dictionary ResourceNameMap = new Dictionary() + { + { Arm, AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId }, + { AadGraph, AzureEnvironment.Endpoint.Graph}, //Only exception that not using xxxResourceId because of implementation of GetTokenAudience + { DataLake, AzureEnvironment.Endpoint.DataLakeEndpointResourceId}, + { KeyVault, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId}, + { Analysis, AzureEnvironment.ExtendedEndpoint.AnalysisServicesEndpointResourceId}, + { Attest, AzureEnvironment.ExtendedEndpoint.AzureAttestationServiceEndpointResourceId }, + { OperationInsights, AzureEnvironment.ExtendedEndpoint.OperationalInsightsEndpointResourceId}, + { Synapse, AzureEnvironment.ExtendedEndpoint.AzureSynapseAnalyticsEndpointResourceId}, + }; + } + } +} diff --git a/src/Accounts/Accounts/help/Az.Accounts.md b/src/Accounts/Accounts/help/Az.Accounts.md index 40662c53cdef..b18d027df9a4 100644 --- a/src/Accounts/Accounts/help/Az.Accounts.md +++ b/src/Accounts/Accounts/help/Az.Accounts.md @@ -47,6 +47,9 @@ machine. Data is collected by default unless you explicitly opt out. ### [Enable-AzureRmAlias](Enable-AzureRmAlias.md) Enables AzureRm prefix aliases for Az modules. +### [Get-AzAccessToken](Get-AzAccessToken.md) +Get raw access token. + ### [Get-AzContext](Get-AzContext.md) Gets the metadata used to authenticate Azure Resource Manager requests. @@ -60,9 +63,6 @@ Get the defaults set by the user in the current context. ### [Get-AzEnvironment](Get-AzEnvironment.md) Get endpoints and metadata for an instance of Azure services. -### [Get-AzProfile](Get-AzProfile.md) -Get the service profiles supported by installed modules. - ### [Get-AzSubscription](Get-AzSubscription.md) Get subscriptions that the current account can access. @@ -96,9 +96,6 @@ Saves the current authentication information for use in other PowerShell session ### [Select-AzContext](Select-AzContext.md) Select a subscription and account to target in Azure PowerShell cmdlets -### [Select-AzProfile](Select-AzProfile.md) -For modules that support multiple service profiles - load the cmdlets corresponding with the given service profile. - ### [Send-Feedback](Send-Feedback.md) Sends feedback to the Azure PowerShell team via a set of guided prompts. diff --git a/src/Accounts/Accounts/help/Get-AzAccessToken.md b/src/Accounts/Accounts/help/Get-AzAccessToken.md new file mode 100644 index 000000000000..7ef4915db4de --- /dev/null +++ b/src/Accounts/Accounts/help/Get-AzAccessToken.md @@ -0,0 +1,99 @@ +--- +external help file: Microsoft.Azure.PowerShell.Cmdlets.Accounts.dll-Help.xml +Module Name: Az.Accounts +online version: +schema: 2.0.0 +--- + +# Get-AzAccessToken + +## SYNOPSIS +Get raw access token + +## SYNTAX + +### KnownResourceTypeName +``` +Get-AzAccessToken -ResourceTypeName [-TenantId ] [-DefaultProfile ] + [] +``` + +## DESCRIPTION +Get access token + +## EXAMPLES + +### Example 1 Get raw access token for ARM endpoint +```powershell +PS C:\> Get-AzAccessToken +``` + +Get access token of ResourceManager endpoint for current account + +### Example 2 Get raw access token for AAD graph endpoint +```powershell +PS C:\> Get-AzAccessToken -ResourceTypeName AadGraph +``` + +Get access token of AAD graph endpoint for current account + +## PARAMETERS + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: Microsoft.Azure.Commands.Common.Authentication.Abstractions.Core.IAzureContextContainer +Parameter Sets: (All) +Aliases: AzContext, AzureRmContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceTypeName +Optional resouce type name, supported values: AadGraph, Analysis, Arm, Attest, DataLake, KeyVault, OperationInsights, Synapse. Default value is Arm if not specified. + +```yaml +Type: System.String +Parameter Sets: KnownResourceTypeName +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TenantId +Optional Tenant Id. Use tenant id of default context if not specified. + +```yaml +Type: System.String +Parameter Sets: (All) + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### None + +## OUTPUTS + +### System.String + +## NOTES + +## RELATED LINKS From effc418260e951fa3e7166232f6171177551aa17 Mon Sep 17 00:00:00 2001 From: "Erich(Renyong) Wang" Date: Fri, 6 Nov 2020 17:01:50 +0800 Subject: [PATCH 2/6] add support for parameter Resource --- src/Accounts/Accounts/Accounts.format.ps1xml | 29 +++++ src/Accounts/Accounts/Models/PSAccessToken.cs | 30 +++++ .../Accounts/Token/GetAzureRmAccessToken.cs | 114 ++++++++++-------- .../Accounts/help/Get-AzAccessToken.md | 36 +++++- .../Authenticators/MsalAccessToken.cs | 2 +- 5 files changed, 158 insertions(+), 53 deletions(-) create mode 100644 src/Accounts/Accounts/Models/PSAccessToken.cs diff --git a/src/Accounts/Accounts/Accounts.format.ps1xml b/src/Accounts/Accounts/Accounts.format.ps1xml index 60a05a222f74..ec0d3787fa7d 100644 --- a/src/Accounts/Accounts/Accounts.format.ps1xml +++ b/src/Accounts/Accounts/Accounts.format.ps1xml @@ -171,6 +171,35 @@ + + Microsoft.Azure.Commands.Profile.Models.PSAccessToken + + Microsoft.Azure.Commands.Profile.Models.PSAccessToken + + + + + + + Token + + + ExpiresOn + + + Type + + + TenantId + + + UserId + + + + + + Microsoft.Azure.Commands.Profile.Models.PSAzureSubscriptionPolicy diff --git a/src/Accounts/Accounts/Models/PSAccessToken.cs b/src/Accounts/Accounts/Models/PSAccessToken.cs new file mode 100644 index 000000000000..959de7f4255d --- /dev/null +++ b/src/Accounts/Accounts/Models/PSAccessToken.cs @@ -0,0 +1,30 @@ +// +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- + +using System; + +namespace Microsoft.Azure.Commands.Profile.Models +{ + public class PSAccessToken + { + public string Token { get; set; } + + public DateTimeOffset ExpiresOn { get; set; } + + public string TenantId { get; set; } + + public string UserId { get; set; } + + public string Type { get; } = "Bearer"; + } +} diff --git a/src/Accounts/Accounts/Token/GetAzureRmAccessToken.cs b/src/Accounts/Accounts/Token/GetAzureRmAccessToken.cs index 58b363a16fd6..abb06c6b0e89 100644 --- a/src/Accounts/Accounts/Token/GetAzureRmAccessToken.cs +++ b/src/Accounts/Accounts/Token/GetAzureRmAccessToken.cs @@ -14,47 +14,51 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Management.Automation; -using System.Net.Http; -using System.Threading; 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.Models; using Microsoft.Azure.Commands.ResourceManager.Common; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; +using Microsoft.Azure.PowerShell.Authenticators; -namespace Microsoft.Azure.Commands.Profile.Token +namespace Microsoft.Azure.Commands.Profile { - [Cmdlet(VerbsCommon.Get, AzureRMConstants.AzureRMPrefix + "AccessToken")] - [OutputType(typeof(string))] + [Cmdlet(VerbsCommon.Get, AzureRMConstants.AzureRMPrefix + "AccessToken", DefaultParameterSetName = KnownResourceNameParameterSet)] + [OutputType(typeof(PSAccessToken))] public class GetAzureRmAccessTokenCommand : AzureRMCmdlet { - private const string AuthorizationHeaderName = "Authorization"; - private const string ResourceUriParameterSet = "ResourceUri"; + private const string ResourceUrlParameterSet = "ResourceUrl"; private const string KnownResourceNameParameterSet = "KnownResourceTypeName"; - //TODO: Support ResourceUri directly - //[Parameter(ParameterSetName = ResourceUriParameterSet, Mandatory = false)] - //public string Resource { get; set; } + [Parameter(ParameterSetName = ResourceUrlParameterSet, + Mandatory = true, + HelpMessage = "Resource url for that you're requesting token, e.g. 'http://graph.windows.net/'.")] + [ValidateNotNullOrEmpty] + [Alias("Resource", "ResourceUri")] + public string ResourceUrl { get; set; } [Parameter(ParameterSetName = KnownResourceNameParameterSet, Mandatory = false, - HelpMessage = "Optional resouce type name, supported values: AadGraph, Analysis, Arm, Attest, DataLake, KeyVault, OperationInsights, Synapse. Default value is Arm if not specified.")] + HelpMessage = "Optional resouce type name, supported values: AadGraph, Analysis, Arm, Attestation, Batch, DataLake, KeyVault, OperationInsights, ResourceManager, Synapse. Default value is Arm if not specified.")] [PSArgumentCompleter( SupportedResourceNames.AadGraph, SupportedResourceNames.Analysis, SupportedResourceNames.Arm, SupportedResourceNames.Attest, + SupportedResourceNames.Batch, SupportedResourceNames.DataLake, SupportedResourceNames.KeyVault, + SupportedResourceNames.ManagedHsm, SupportedResourceNames.OperationInsights, + SupportedResourceNames.ResourceManager, SupportedResourceNames.Synapse )] public string ResourceTypeName { get; set; } //Use tenant in default context if not specified + //TODO: Should not specify TenantId for MSI, CloudShell(?) [Parameter(Mandatory = false, HelpMessage = "Optional Tenant Id. Use tenant id of default context if not specified.")] public string TenantId { get; set; } @@ -62,69 +66,81 @@ public override void ExecuteCmdlet() { base.ExecuteCmdlet(); - string resourceId = null; + string resourceUrlOrId; - if (ResourceTypeName == null) + if (ParameterSetName == KnownResourceNameParameterSet) { - ResourceTypeName = SupportedResourceNames.Arm; + if (ResourceTypeName == null) + { + ResourceTypeName = SupportedResourceNames.Arm; + } + if (!SupportedResourceNames.ResourceNameMap.ContainsKey(ResourceTypeName)) + { + throw new ArgumentException(Properties.Resources.InvalidResourceTypeName.FormatInvariant(ResourceTypeName), nameof(ResourceTypeName)); + } + resourceUrlOrId = SupportedResourceNames.ResourceNameMap[ResourceTypeName]; } - if (!SupportedResourceNames.ResourceNameMap.ContainsKey(ResourceTypeName)) + else { - throw new ArgumentException(Properties.Resources.InvalidResourceTypeName.FormatInvariant(ResourceTypeName), nameof(ResourceTypeName)); + resourceUrlOrId = ResourceUrl; } - resourceId = SupportedResourceNames.ResourceNameMap[ResourceTypeName]; - - resourceId = string.IsNullOrEmpty(resourceId) ? AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId : resourceId; - IAzureContext context = DefaultContext; - if (!string.IsNullOrEmpty(TenantId) && !string.Equals(context.Tenant.Id, TenantId, StringComparison.OrdinalIgnoreCase)) + if(TenantId == null) { - var profile = DefaultProfile as AzureRmProfile; - context = profile.Contexts.FirstOrDefault(c => - string.Equals(c.Value.Tenant.Id, TenantId, StringComparison.OrdinalIgnoreCase)).Value; - if (context == null) - { - throw new ArgumentException(Properties.Resources.InvalidTenantId.FormatInvariant(TenantId), nameof(TenantId)); - } + TenantId = context.Tenant?.Id; } - var credential = AzureSession.Instance.AuthenticationFactory.GetServiceClientCredentials( - context, - resourceId); - var requestMessage = new HttpRequestMessage(); - credential.ProcessHttpRequestAsync(requestMessage, default(CancellationToken)).ConfigureAwait(false).GetAwaiter().GetResult(); - if (requestMessage.Headers.Contains(AuthorizationHeaderName)) + + IAccessToken accessToken = AzureSession.Instance.AuthenticationFactory.Authenticate( + context.Account, + context.Environment, + TenantId, + null, + ShowDialog.Never, + null, + null, + resourceUrlOrId); + + var result = new PSAccessToken() { - var token = requestMessage.Headers.GetValues(AuthorizationHeaderName) - ?.FirstOrDefault()?.Substring("Bearer ".Length); - WriteObject(token); - } + Token = accessToken.AccessToken, + TenantId = TenantId, + UserId = accessToken.UserId, + }; + result.ExpiresOn = (accessToken as MsalAccessToken)?.ExpiredOn ?? result.ExpiresOn; + + WriteObject(result); } internal class SupportedResourceNames { - //TODO: Support 'Batch' and 'ManagedHsm', need to upate AzureEnvironmentExtensions.GetTokenAudience() to support more endpoints - public const string Arm = "Arm"; public const string AadGraph = "AadGraph"; + public const string Batch = "Batch"; public const string DataLake = "DataLake"; public const string KeyVault = "KeyVault"; + public const string ResourceManager = "ResourceManager"; //endpoint is same as Arm public const string Analysis = "Analysis"; - public const string Attest = "Attest"; + public const string Attest = "Attestation"; public const string OperationInsights = "OperationInsights"; public const string Synapse = "Synapse"; + public const string ManagedHsm = "ManagedHsm"; internal static Dictionary ResourceNameMap = new Dictionary() { { Arm, AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId }, - { AadGraph, AzureEnvironment.Endpoint.Graph}, //Only exception that not using xxxResourceId because of implementation of GetTokenAudience - { DataLake, AzureEnvironment.Endpoint.DataLakeEndpointResourceId}, - { KeyVault, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId}, - { Analysis, AzureEnvironment.ExtendedEndpoint.AnalysisServicesEndpointResourceId}, + { AadGraph, AzureEnvironment.Endpoint.GraphEndpointResourceId }, + { Batch, AzureEnvironment.Endpoint.BatchEndpointResourceId }, + { DataLake, AzureEnvironment.Endpoint.DataLakeEndpointResourceId }, + { KeyVault, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId }, + { ResourceManager, AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId }, + + { Analysis, AzureEnvironment.ExtendedEndpoint.AnalysisServicesEndpointResourceId }, { Attest, AzureEnvironment.ExtendedEndpoint.AzureAttestationServiceEndpointResourceId }, - { OperationInsights, AzureEnvironment.ExtendedEndpoint.OperationalInsightsEndpointResourceId}, - { Synapse, AzureEnvironment.ExtendedEndpoint.AzureSynapseAnalyticsEndpointResourceId}, + { OperationInsights, AzureEnvironment.ExtendedEndpoint.OperationalInsightsEndpointResourceId }, + { Synapse, AzureEnvironment.ExtendedEndpoint.AzureSynapseAnalyticsEndpointResourceId }, + { ManagedHsm, AzureEnvironment.ExtendedEndpoint.ManagedHsmServiceEndpointResourceId } }; } } diff --git a/src/Accounts/Accounts/help/Get-AzAccessToken.md b/src/Accounts/Accounts/help/Get-AzAccessToken.md index 7ef4915db4de..7e6ed50f133a 100644 --- a/src/Accounts/Accounts/help/Get-AzAccessToken.md +++ b/src/Accounts/Accounts/help/Get-AzAccessToken.md @@ -12,9 +12,16 @@ Get raw access token ## SYNTAX -### KnownResourceTypeName +### KnownResourceTypeName (Default) ``` -Get-AzAccessToken -ResourceTypeName [-TenantId ] [-DefaultProfile ] +Get-AzAccessToken [-ResourceTypeName ] [-TenantId ] [-DefaultProfile ] + [] +``` + +### ResourceUrl +When using ResourceUrl, please make sure the value is correct for current Azure environment. You may refer to the value of `(Get-AzContext).Environment`. +``` +Get-AzAccessToken -ResourceUrl [-TenantId ] [-DefaultProfile ] [] ``` @@ -37,6 +44,13 @@ PS C:\> Get-AzAccessToken -ResourceTypeName AadGraph Get access token of AAD graph endpoint for current account +### Example 3 Get raw access token for AAD graph endpoint +```powershell +PS C:\> Get-AzAccessToken -Resource "https://graph.windows.net/" +``` + +Get access token of AAD graph endpoint for current account + ## PARAMETERS ### -DefaultProfile @@ -55,13 +69,28 @@ Accept wildcard characters: False ``` ### -ResourceTypeName -Optional resouce type name, supported values: AadGraph, Analysis, Arm, Attest, DataLake, KeyVault, OperationInsights, Synapse. Default value is Arm if not specified. +Optional resouce type name, supported values: AadGraph, Analysis, Arm, Attestation, Batch, DataLake, KeyVault, OperationInsights, ResourceManager, Synapse. Default value is Arm if not specified. ```yaml Type: System.String Parameter Sets: KnownResourceTypeName Aliases: +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceUrl +Resource url for that you're requesting token, e.g. 'http://graph.windows.net/'. + +```yaml +Type: System.String +Parameter Sets: ResourceUrl +Aliases: Resource, ResourceUri + Required: True Position: Named Default value: None @@ -75,6 +104,7 @@ Optional Tenant Id. Use tenant id of default context if not specified. ```yaml Type: System.String Parameter Sets: (All) +Aliases: Required: False Position: Named diff --git a/src/Accounts/Authenticators/MsalAccessToken.cs b/src/Accounts/Authenticators/MsalAccessToken.cs index 41c506f718c0..d3b4b7074a4d 100644 --- a/src/Accounts/Authenticators/MsalAccessToken.cs +++ b/src/Accounts/Authenticators/MsalAccessToken.cs @@ -39,7 +39,7 @@ public class MsalAccessToken : IAccessToken public IDictionary ExtendedProperties { get; } = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); - private DateTimeOffset ExpiredOn { get; set; } + public DateTimeOffset ExpiredOn { get; set; } private readonly static TimeSpan ExpirationThreshold = TimeSpan.FromMinutes(5); From c53721ae867dd99aa0616ec75414e442e440e9f6 Mon Sep 17 00:00:00 2001 From: "Erich(Renyong) Wang" Date: Fri, 6 Nov 2020 17:18:56 +0800 Subject: [PATCH 3/6] update resource type name --- .../Accounts/Properties/Resources.Designer.cs | 9 --------- .../Accounts/Properties/Resources.resx | 3 --- .../Accounts/Token/GetAzureRmAccessToken.cs | 20 +++++++++---------- .../Accounts/help/Get-AzAccessToken.md | 2 +- 4 files changed, 11 insertions(+), 23 deletions(-) diff --git a/src/Accounts/Accounts/Properties/Resources.Designer.cs b/src/Accounts/Accounts/Properties/Resources.Designer.cs index 10c812f79269..7056fda4b882 100644 --- a/src/Accounts/Accounts/Properties/Resources.Designer.cs +++ b/src/Accounts/Accounts/Properties/Resources.Designer.cs @@ -609,15 +609,6 @@ internal static string InvalidSubscriptionId { } } - /// - /// Looks up a localized string similar to Could not find TenantId "{0}" in logged-in contexts. Please make sure you have logged into the tenant, e.g. Connect-AzAccount -Tenant xxx. - /// - internal static string InvalidTenantId { - get { - return ResourceManager.GetString("InvalidTenantId", resourceCulture); - } - } - /// /// Looks up a localized string similar to {0} account in environment '{1}'. /// diff --git a/src/Accounts/Accounts/Properties/Resources.resx b/src/Accounts/Accounts/Properties/Resources.resx index ba9e75094a41..f56eda9fd368 100644 --- a/src/Accounts/Accounts/Properties/Resources.resx +++ b/src/Accounts/Accounts/Properties/Resources.resx @@ -522,7 +522,4 @@ The specified ResourceTypeName "{0}" is not supported, please provide a valid value. e.g. Arm, AadGraph, etc. - - Could not find TenantId "{0}" in logged-in contexts. Please make sure you have logged into the tenant, e.g. Connect-AzAccount -Tenant xxx - \ No newline at end of file diff --git a/src/Accounts/Accounts/Token/GetAzureRmAccessToken.cs b/src/Accounts/Accounts/Token/GetAzureRmAccessToken.cs index abb06c6b0e89..82cbcf439c50 100644 --- a/src/Accounts/Accounts/Token/GetAzureRmAccessToken.cs +++ b/src/Accounts/Accounts/Token/GetAzureRmAccessToken.cs @@ -41,17 +41,17 @@ public class GetAzureRmAccessTokenCommand : AzureRMCmdlet [Parameter(ParameterSetName = KnownResourceNameParameterSet, Mandatory = false, - HelpMessage = "Optional resouce type name, supported values: AadGraph, Analysis, Arm, Attestation, Batch, DataLake, KeyVault, OperationInsights, ResourceManager, Synapse. Default value is Arm if not specified.")] + HelpMessage = "Optional resouce type name, supported values: AadGraph, AnalysisServices, Arm, Attestation, Batch, DataLake, KeyVault, OperationalInsights, ResourceManager, Synapse. Default value is Arm if not specified.")] [PSArgumentCompleter( SupportedResourceNames.AadGraph, - SupportedResourceNames.Analysis, + SupportedResourceNames.AnalysisServices, SupportedResourceNames.Arm, - SupportedResourceNames.Attest, + SupportedResourceNames.Attestation, SupportedResourceNames.Batch, SupportedResourceNames.DataLake, SupportedResourceNames.KeyVault, SupportedResourceNames.ManagedHsm, - SupportedResourceNames.OperationInsights, + SupportedResourceNames.OperationalInsights, SupportedResourceNames.ResourceManager, SupportedResourceNames.Synapse )] @@ -121,9 +121,9 @@ internal class SupportedResourceNames public const string KeyVault = "KeyVault"; public const string ResourceManager = "ResourceManager"; //endpoint is same as Arm - public const string Analysis = "Analysis"; - public const string Attest = "Attestation"; - public const string OperationInsights = "OperationInsights"; + public const string AnalysisServices = "AnalysisServices"; + public const string Attestation = "Attestation"; + public const string OperationalInsights = "OperationalInsights"; public const string Synapse = "Synapse"; public const string ManagedHsm = "ManagedHsm"; @@ -136,9 +136,9 @@ internal class SupportedResourceNames { KeyVault, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId }, { ResourceManager, AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId }, - { Analysis, AzureEnvironment.ExtendedEndpoint.AnalysisServicesEndpointResourceId }, - { Attest, AzureEnvironment.ExtendedEndpoint.AzureAttestationServiceEndpointResourceId }, - { OperationInsights, AzureEnvironment.ExtendedEndpoint.OperationalInsightsEndpointResourceId }, + { AnalysisServices, AzureEnvironment.ExtendedEndpoint.AnalysisServicesEndpointResourceId }, + { Attestation, AzureEnvironment.ExtendedEndpoint.AzureAttestationServiceEndpointResourceId }, + { OperationalInsights, AzureEnvironment.ExtendedEndpoint.OperationalInsightsEndpointResourceId }, { Synapse, AzureEnvironment.ExtendedEndpoint.AzureSynapseAnalyticsEndpointResourceId }, { ManagedHsm, AzureEnvironment.ExtendedEndpoint.ManagedHsmServiceEndpointResourceId } }; diff --git a/src/Accounts/Accounts/help/Get-AzAccessToken.md b/src/Accounts/Accounts/help/Get-AzAccessToken.md index 7e6ed50f133a..b03cfa587b64 100644 --- a/src/Accounts/Accounts/help/Get-AzAccessToken.md +++ b/src/Accounts/Accounts/help/Get-AzAccessToken.md @@ -69,7 +69,7 @@ Accept wildcard characters: False ``` ### -ResourceTypeName -Optional resouce type name, supported values: AadGraph, Analysis, Arm, Attestation, Batch, DataLake, KeyVault, OperationInsights, ResourceManager, Synapse. Default value is Arm if not specified. +Optional resouce type name, supported values: AadGraph, AnalysisServices, Arm, Attestation, Batch, DataLake, KeyVault, OperationalInsights, ResourceManager, Synapse. Default value is Arm if not specified. ```yaml Type: System.String From 9cd7bf2fedfcac1668fc500c4185416ddedb0e3f Mon Sep 17 00:00:00 2001 From: "Erich(Renyong) Wang" Date: Mon, 9 Nov 2020 23:40:41 +0800 Subject: [PATCH 4/6] use ExpiresOn --- src/Accounts/Accounts/Token/GetAzureRmAccessToken.cs | 2 +- src/Accounts/Authenticators/MsalAccessToken.cs | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Accounts/Accounts/Token/GetAzureRmAccessToken.cs b/src/Accounts/Accounts/Token/GetAzureRmAccessToken.cs index 82cbcf439c50..d493f27787a4 100644 --- a/src/Accounts/Accounts/Token/GetAzureRmAccessToken.cs +++ b/src/Accounts/Accounts/Token/GetAzureRmAccessToken.cs @@ -107,7 +107,7 @@ public override void ExecuteCmdlet() TenantId = TenantId, UserId = accessToken.UserId, }; - result.ExpiresOn = (accessToken as MsalAccessToken)?.ExpiredOn ?? result.ExpiresOn; + result.ExpiresOn = (accessToken as MsalAccessToken)?.ExpiresOn ?? result.ExpiresOn; WriteObject(result); } diff --git a/src/Accounts/Authenticators/MsalAccessToken.cs b/src/Accounts/Authenticators/MsalAccessToken.cs index d3b4b7074a4d..57ebfb383b10 100644 --- a/src/Accounts/Authenticators/MsalAccessToken.cs +++ b/src/Accounts/Authenticators/MsalAccessToken.cs @@ -39,7 +39,7 @@ public class MsalAccessToken : IAccessToken public IDictionary ExtendedProperties { get; } = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); - public DateTimeOffset ExpiredOn { get; set; } + public DateTimeOffset ExpiresOn { get; set; } private readonly static TimeSpan ExpirationThreshold = TimeSpan.FromMinutes(5); @@ -53,7 +53,7 @@ public MsalAccessToken(TokenCredential tokenCredential, TokenRequestContext toke TokenCredential = tokenCredential; TokenRequestContext = tokenRequestContext; AccessToken = token; - ExpiredOn = expiresOn; + ExpiresOn = expiresOn; UserId = userId; TenantId = tenantId; HomeAccountId = homeAccountId; @@ -98,7 +98,7 @@ private void Renew() { var token = TokenCredential.GetToken(TokenRequestContext, default(CancellationToken)); AccessToken = token.Token; - ExpiredOn = token.ExpiresOn; + ExpiresOn = token.ExpiresOn; } } @@ -110,7 +110,7 @@ private bool IsNearExpiration() return true; } #endif - var timeUntilExpiration = ExpiredOn - DateTimeOffset.UtcNow; + var timeUntilExpiration = ExpiresOn - DateTimeOffset.UtcNow; return timeUntilExpiration < ExpirationThreshold; } } From ae29e9c1ea9c0ed6b1b4893404c57add0804ab4a Mon Sep 17 00:00:00 2001 From: Yeming Liu Date: Tue, 10 Nov 2020 10:25:17 +0800 Subject: [PATCH 5/6] fix static analysis --- src/Accounts/Accounts/help/Get-AzAccessToken.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Accounts/Accounts/help/Get-AzAccessToken.md b/src/Accounts/Accounts/help/Get-AzAccessToken.md index b03cfa587b64..eaf6368867c4 100644 --- a/src/Accounts/Accounts/help/Get-AzAccessToken.md +++ b/src/Accounts/Accounts/help/Get-AzAccessToken.md @@ -1,7 +1,7 @@ --- external help file: Microsoft.Azure.PowerShell.Cmdlets.Accounts.dll-Help.xml Module Name: Az.Accounts -online version: +online version: https://docs.microsoft.com/en-us/powershell/module/az.accounts/get-azaccesstoken schema: 2.0.0 --- From 45b14e8f58f974afc2e51ac8b0c685ee19b7cdfc Mon Sep 17 00:00:00 2001 From: "Erich(Renyong) Wang" Date: Tue, 10 Nov 2020 11:22:18 +0800 Subject: [PATCH 6/6] fix help error --- src/Accounts/Accounts/help/Get-AzAccessToken.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Accounts/Accounts/help/Get-AzAccessToken.md b/src/Accounts/Accounts/help/Get-AzAccessToken.md index eaf6368867c4..5c09aa4ccdec 100644 --- a/src/Accounts/Accounts/help/Get-AzAccessToken.md +++ b/src/Accounts/Accounts/help/Get-AzAccessToken.md @@ -8,7 +8,7 @@ schema: 2.0.0 # Get-AzAccessToken ## SYNOPSIS -Get raw access token +Get raw access token. When using -ResourceUrl, please make sure the value does match current Azure environment. You may refer to the value of `(Get-AzContext).Environment`. ## SYNTAX @@ -19,7 +19,6 @@ Get-AzAccessToken [-ResourceTypeName ] [-TenantId ] [-DefaultPro ``` ### ResourceUrl -When using ResourceUrl, please make sure the value is correct for current Azure environment. You may refer to the value of `(Get-AzContext).Environment`. ``` Get-AzAccessToken -ResourceUrl [-TenantId ] [-DefaultProfile ] []