Skip to content

Commit f98103c

Browse files
committed
add cmdlet Get-AzAccessToken
1 parent 0e8cf9c commit f98103c

File tree

7 files changed

+259
-7
lines changed

7 files changed

+259
-7
lines changed

src/Accounts/Accounts/Az.Accounts.psd1

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ CmdletsToExport = 'Disable-AzDataCollection', 'Disable-AzContextAutosave',
106106
'Disconnect-AzAccount', 'Get-AzContextAutosaveSetting',
107107
'Set-AzDefault', 'Get-AzDefault', 'Clear-AzDefault',
108108
'Register-AzModule', 'Enable-AzureRmAlias', 'Disable-AzureRmAlias',
109-
'Uninstall-AzureRm', 'Invoke-AzRestMethod'
109+
'Uninstall-AzureRm', 'Invoke-AzRestMethod', 'Get-AzAccessToken'
110110

111111
# Variables to export from this module
112112
# VariablesToExport = @()

src/Accounts/Accounts/ChangeLog.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
- Additional information about change #1
1919
-->
2020
## Upcoming Release
21+
* Add new cmdlet `Get-AzAccessToken`
2122
* Supported interrupting login by hitting <kbd>CTRL</kbd>+<kbd>C</kbd>
2223
* Fixed an issue causing `Connect-AzAccount -KeyVaultAccessToken` not working [#13127]
2324
* Fixed null reference and method case insensitive in `Invoke-AzRestMethod`

src/Accounts/Accounts/Properties/Resources.Designer.cs

Lines changed: 18 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/Accounts/Accounts/Properties/Resources.resx

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -519,4 +519,10 @@
519519
<data name="SuggestToUseDeviceCodeAuth" xml:space="preserve">
520520
<value>Please run 'Connect-AzAccount -DeviceCode' if browser is not supported in this session.</value>
521521
</data>
522+
<data name="InvalidResourceTypeName" xml:space="preserve">
523+
<value>The specified ResourceTypeName "{0}" is not supported, please provide a valid value. e.g. Arm, AadGraph, etc.</value>
524+
</data>
525+
<data name="InvalidTenantId" xml:space="preserve">
526+
<value>Could not find TenantId "{0}" in logged-in contexts. Please make sure you have logged into the tenant, e.g. Connect-AzAccount -Tenant xxx</value>
527+
</data>
522528
</root>
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
// ----------------------------------------------------------------------------------
2+
//
3+
// Copyright Microsoft Corporation
4+
// Licensed under the Apache License, Version 2.0 (the "License");
5+
// you may not use this file except in compliance with the License.
6+
// You may obtain a copy of the License at
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
// Unless required by applicable law or agreed to in writing, software
9+
// distributed under the License is distributed on an "AS IS" BASIS,
10+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
// See the License for the specific language governing permissions and
12+
// limitations under the License.
13+
// ----------------------------------------------------------------------------------
14+
15+
using System;
16+
using System.Collections.Generic;
17+
using System.Linq;
18+
using System.Management.Automation;
19+
using System.Net.Http;
20+
using System.Threading;
21+
22+
using Microsoft.Azure.Commands.Common.Authentication;
23+
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
24+
using Microsoft.Azure.Commands.Common.Authentication.Models;
25+
using Microsoft.Azure.Commands.ResourceManager.Common;
26+
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
27+
28+
namespace Microsoft.Azure.Commands.Profile.Token
29+
{
30+
[Cmdlet(VerbsCommon.Get, AzureRMConstants.AzureRMPrefix + "AccessToken")]
31+
[OutputType(typeof(string))]
32+
public class GetAzureRmAccessTokenCommand : AzureRMCmdlet
33+
{
34+
private const string AuthorizationHeaderName = "Authorization";
35+
private const string ResourceUriParameterSet = "ResourceUri";
36+
private const string KnownResourceNameParameterSet = "KnownResourceTypeName";
37+
38+
//TODO: Support ResourceUri directly
39+
//[Parameter(ParameterSetName = ResourceUriParameterSet, Mandatory = false)]
40+
//public string Resource { get; set; }
41+
42+
[Parameter(ParameterSetName = KnownResourceNameParameterSet,
43+
Mandatory = false,
44+
HelpMessage = "Optional resouce type name, supported values: AadGraph, Analysis, Arm, Attest, DataLake, KeyVault, OperationInsights, Synapse. Default value is Arm if not specified.")]
45+
[PSArgumentCompleter(
46+
SupportedResourceNames.AadGraph,
47+
SupportedResourceNames.Analysis,
48+
SupportedResourceNames.Arm,
49+
SupportedResourceNames.Attest,
50+
SupportedResourceNames.DataLake,
51+
SupportedResourceNames.KeyVault,
52+
SupportedResourceNames.OperationInsights,
53+
SupportedResourceNames.Synapse
54+
)]
55+
public string ResourceTypeName { get; set; }
56+
57+
//Use tenant in default context if not specified
58+
[Parameter(Mandatory = false, HelpMessage = "Optional Tenant Id. Use tenant id of default context if not specified.")]
59+
public string TenantId { get; set; }
60+
61+
public override void ExecuteCmdlet()
62+
{
63+
base.ExecuteCmdlet();
64+
65+
string resourceId = null;
66+
67+
if (ResourceTypeName == null)
68+
{
69+
ResourceTypeName = SupportedResourceNames.Arm;
70+
}
71+
if (!SupportedResourceNames.ResourceNameMap.ContainsKey(ResourceTypeName))
72+
{
73+
throw new ArgumentException(Properties.Resources.InvalidResourceTypeName.FormatInvariant(ResourceTypeName), nameof(ResourceTypeName));
74+
}
75+
76+
resourceId = SupportedResourceNames.ResourceNameMap[ResourceTypeName];
77+
78+
resourceId = string.IsNullOrEmpty(resourceId) ? AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId : resourceId;
79+
80+
IAzureContext context = DefaultContext;
81+
if (!string.IsNullOrEmpty(TenantId) && !string.Equals(context.Tenant.Id, TenantId, StringComparison.OrdinalIgnoreCase))
82+
{
83+
var profile = DefaultProfile as AzureRmProfile;
84+
context = profile.Contexts.FirstOrDefault(c =>
85+
string.Equals(c.Value.Tenant.Id, TenantId, StringComparison.OrdinalIgnoreCase)).Value;
86+
if (context == null)
87+
{
88+
throw new ArgumentException(Properties.Resources.InvalidTenantId.FormatInvariant(TenantId), nameof(TenantId));
89+
}
90+
}
91+
var credential = AzureSession.Instance.AuthenticationFactory.GetServiceClientCredentials(
92+
context,
93+
resourceId);
94+
var requestMessage = new HttpRequestMessage();
95+
credential.ProcessHttpRequestAsync(requestMessage, default(CancellationToken)).ConfigureAwait(false).GetAwaiter().GetResult();
96+
if (requestMessage.Headers.Contains(AuthorizationHeaderName))
97+
{
98+
var token = requestMessage.Headers.GetValues(AuthorizationHeaderName)
99+
?.FirstOrDefault()?.Substring("Bearer ".Length);
100+
WriteObject(token);
101+
}
102+
}
103+
104+
internal class SupportedResourceNames
105+
{
106+
//TODO: Support 'Batch' and 'ManagedHsm', need to upate AzureEnvironmentExtensions.GetTokenAudience() to support more endpoints
107+
108+
public const string Arm = "Arm";
109+
public const string AadGraph = "AadGraph";
110+
public const string DataLake = "DataLake";
111+
public const string KeyVault = "KeyVault";
112+
113+
public const string Analysis = "Analysis";
114+
public const string Attest = "Attest";
115+
public const string OperationInsights = "OperationInsights";
116+
public const string Synapse = "Synapse";
117+
118+
internal static Dictionary<string, string> ResourceNameMap = new Dictionary<string, string>()
119+
{
120+
{ Arm, AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId },
121+
{ AadGraph, AzureEnvironment.Endpoint.Graph}, //Only exception that not using xxxResourceId because of implementation of GetTokenAudience
122+
{ DataLake, AzureEnvironment.Endpoint.DataLakeEndpointResourceId},
123+
{ KeyVault, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId},
124+
{ Analysis, AzureEnvironment.ExtendedEndpoint.AnalysisServicesEndpointResourceId},
125+
{ Attest, AzureEnvironment.ExtendedEndpoint.AzureAttestationServiceEndpointResourceId },
126+
{ OperationInsights, AzureEnvironment.ExtendedEndpoint.OperationalInsightsEndpointResourceId},
127+
{ Synapse, AzureEnvironment.ExtendedEndpoint.AzureSynapseAnalyticsEndpointResourceId},
128+
};
129+
}
130+
}
131+
}

src/Accounts/Accounts/help/Az.Accounts.md

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,9 @@ machine. Data is collected by default unless you explicitly opt out.
4747
### [Enable-AzureRmAlias](Enable-AzureRmAlias.md)
4848
Enables AzureRm prefix aliases for Az modules.
4949

50+
### [Get-AzAccessToken](Get-AzAccessToken.md)
51+
Get raw access token.
52+
5053
### [Get-AzContext](Get-AzContext.md)
5154
Gets the metadata used to authenticate Azure Resource Manager requests.
5255

@@ -60,9 +63,6 @@ Get the defaults set by the user in the current context.
6063
### [Get-AzEnvironment](Get-AzEnvironment.md)
6164
Get endpoints and metadata for an instance of Azure services.
6265

63-
### [Get-AzProfile](Get-AzProfile.md)
64-
Get the service profiles supported by installed modules.
65-
6666
### [Get-AzSubscription](Get-AzSubscription.md)
6767
Get subscriptions that the current account can access.
6868

@@ -96,9 +96,6 @@ Saves the current authentication information for use in other PowerShell session
9696
### [Select-AzContext](Select-AzContext.md)
9797
Select a subscription and account to target in Azure PowerShell cmdlets
9898

99-
### [Select-AzProfile](Select-AzProfile.md)
100-
For modules that support multiple service profiles - load the cmdlets corresponding with the given service profile.
101-
10299
### [Send-Feedback](Send-Feedback.md)
103100
Sends feedback to the Azure PowerShell team via a set of guided prompts.
104101

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
---
2+
external help file: Microsoft.Azure.PowerShell.Cmdlets.Accounts.dll-Help.xml
3+
Module Name: Az.Accounts
4+
online version:
5+
schema: 2.0.0
6+
---
7+
8+
# Get-AzAccessToken
9+
10+
## SYNOPSIS
11+
Get raw access token
12+
13+
## SYNTAX
14+
15+
### KnownResourceTypeName
16+
```
17+
Get-AzAccessToken -ResourceTypeName <String> [-TenantId <String>] [-DefaultProfile <IAzureContextContainer>]
18+
[<CommonParameters>]
19+
```
20+
21+
## DESCRIPTION
22+
Get access token
23+
24+
## EXAMPLES
25+
26+
### Example 1 Get raw access token for ARM endpoint
27+
```powershell
28+
PS C:\> Get-AzAccessToken
29+
```
30+
31+
Get access token of ResourceManager endpoint for current account
32+
33+
### Example 2 Get raw access token for AAD graph endpoint
34+
```powershell
35+
PS C:\> Get-AzAccessToken -ResourceTypeName AadGraph
36+
```
37+
38+
Get access token of AAD graph endpoint for current account
39+
40+
## PARAMETERS
41+
42+
### -DefaultProfile
43+
The credentials, account, tenant, and subscription used for communication with Azure.
44+
45+
```yaml
46+
Type: Microsoft.Azure.Commands.Common.Authentication.Abstractions.Core.IAzureContextContainer
47+
Parameter Sets: (All)
48+
Aliases: AzContext, AzureRmContext, AzureCredential
49+
50+
Required: False
51+
Position: Named
52+
Default value: None
53+
Accept pipeline input: False
54+
Accept wildcard characters: False
55+
```
56+
57+
### -ResourceTypeName
58+
Optional resouce type name, supported values: AadGraph, Analysis, Arm, Attest, DataLake, KeyVault, OperationInsights, Synapse. Default value is Arm if not specified.
59+
60+
```yaml
61+
Type: System.String
62+
Parameter Sets: KnownResourceTypeName
63+
Aliases:
64+
65+
Required: True
66+
Position: Named
67+
Default value: None
68+
Accept pipeline input: False
69+
Accept wildcard characters: False
70+
```
71+
72+
### -TenantId
73+
Optional Tenant Id. Use tenant id of default context if not specified.
74+
75+
```yaml
76+
Type: System.String
77+
Parameter Sets: (All)
78+
79+
Required: False
80+
Position: Named
81+
Default value: None
82+
Accept pipeline input: False
83+
Accept wildcard characters: False
84+
```
85+
86+
### CommonParameters
87+
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).
88+
89+
## INPUTS
90+
91+
### None
92+
93+
## OUTPUTS
94+
95+
### System.String
96+
97+
## NOTES
98+
99+
## RELATED LINKS

0 commit comments

Comments
 (0)