Skip to content

Commit 8bd6a19

Browse files
erich-wangisra-fel
andauthored
Add cmdlet Get-AzAccessToken (#13398)
Force merge due to random failure * add cmdlet Get-AzAccessToken * add support for parameter Resource * update resource type name * use ExpiresOn * fix static analysis * fix help error Co-authored-by: Yeming Liu <[email protected]>
1 parent 9e2b654 commit 8bd6a19

File tree

10 files changed

+355
-11
lines changed

10 files changed

+355
-11
lines changed

src/Accounts/Accounts/Accounts.format.ps1xml

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,35 @@
171171
</TableRowEntries>
172172
</TableControl>
173173
</View>
174+
<View>
175+
<Name>Microsoft.Azure.Commands.Profile.Models.PSAccessToken</Name>
176+
<ViewSelectedBy>
177+
<TypeName>Microsoft.Azure.Commands.Profile.Models.PSAccessToken</TypeName>
178+
</ViewSelectedBy>
179+
<ListControl>
180+
<ListEntries>
181+
<ListEntry>
182+
<ListItems>
183+
<ListItem>
184+
<PropertyName>Token</PropertyName>
185+
</ListItem>
186+
<ListItem>
187+
<PropertyName>ExpiresOn</PropertyName>
188+
</ListItem>
189+
<ListItem>
190+
<PropertyName>Type</PropertyName>
191+
</ListItem>
192+
<ListItem>
193+
<PropertyName>TenantId</PropertyName>
194+
</ListItem>
195+
<ListItem>
196+
<PropertyName>UserId</PropertyName>
197+
</ListItem>
198+
</ListItems>
199+
</ListEntry>
200+
</ListEntries>
201+
</ListControl>
202+
</View>
174203
<View>
175204
<Name>Microsoft.Azure.Commands.Profile.Models.PSAzureSubscriptionPolicy</Name>
176205
<ViewSelectedBy>

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+
* Added new cmdlet `Get-AzAccessToken`
2122
* Fixed an issue that error happens if user profile path is inaccessible
2223
* Fixed an issue causing Write-Object error during Connect-AzAccount [#13419]
2324
* Added parameter "ContainerRegistryEndpointSuffix" to: `Add-AzEnvironment`, `Set-AzEnvironment`
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
//
2+
// Copyright Microsoft Corporation
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
// http://www.apache.org/licenses/LICENSE-2.0
7+
// Unless required by applicable law or agreed to in writing, software
8+
// distributed under the License is distributed on an "AS IS" BASIS,
9+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10+
// See the License for the specific language governing permissions and
11+
// limitations under the License.
12+
// ----------------------------------------------------------------------------------
13+
14+
using System;
15+
16+
namespace Microsoft.Azure.Commands.Profile.Models
17+
{
18+
public class PSAccessToken
19+
{
20+
public string Token { get; set; }
21+
22+
public DateTimeOffset ExpiresOn { get; set; }
23+
24+
public string TenantId { get; set; }
25+
26+
public string UserId { get; set; }
27+
28+
public string Type { get; } = "Bearer";
29+
}
30+
}

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

Lines changed: 9 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: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -519,6 +519,9 @@
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>
522525
<data name="FallbackContextSaveModeDueCacheCheckError" xml:space="preserve">
523526
<value>INITIALIZATION: Fallback context save mode to process because of error during checking token cache persistence: {0}.</value>
524527
</data>
Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
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.Management.Automation;
18+
19+
using Microsoft.Azure.Commands.Common.Authentication;
20+
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
21+
using Microsoft.Azure.Commands.Profile.Models;
22+
using Microsoft.Azure.Commands.ResourceManager.Common;
23+
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
24+
using Microsoft.Azure.PowerShell.Authenticators;
25+
26+
namespace Microsoft.Azure.Commands.Profile
27+
{
28+
[Cmdlet(VerbsCommon.Get, AzureRMConstants.AzureRMPrefix + "AccessToken", DefaultParameterSetName = KnownResourceNameParameterSet)]
29+
[OutputType(typeof(PSAccessToken))]
30+
public class GetAzureRmAccessTokenCommand : AzureRMCmdlet
31+
{
32+
private const string ResourceUrlParameterSet = "ResourceUrl";
33+
private const string KnownResourceNameParameterSet = "KnownResourceTypeName";
34+
35+
[Parameter(ParameterSetName = ResourceUrlParameterSet,
36+
Mandatory = true,
37+
HelpMessage = "Resource url for that you're requesting token, e.g. 'http://graph.windows.net/'.")]
38+
[ValidateNotNullOrEmpty]
39+
[Alias("Resource", "ResourceUri")]
40+
public string ResourceUrl { get; set; }
41+
42+
[Parameter(ParameterSetName = KnownResourceNameParameterSet,
43+
Mandatory = false,
44+
HelpMessage = "Optional resouce type name, supported values: AadGraph, AnalysisServices, Arm, Attestation, Batch, DataLake, KeyVault, OperationalInsights, ResourceManager, Synapse. Default value is Arm if not specified.")]
45+
[PSArgumentCompleter(
46+
SupportedResourceNames.AadGraph,
47+
SupportedResourceNames.AnalysisServices,
48+
SupportedResourceNames.Arm,
49+
SupportedResourceNames.Attestation,
50+
SupportedResourceNames.Batch,
51+
SupportedResourceNames.DataLake,
52+
SupportedResourceNames.KeyVault,
53+
SupportedResourceNames.ManagedHsm,
54+
SupportedResourceNames.OperationalInsights,
55+
SupportedResourceNames.ResourceManager,
56+
SupportedResourceNames.Synapse
57+
)]
58+
public string ResourceTypeName { get; set; }
59+
60+
//Use tenant in default context if not specified
61+
//TODO: Should not specify TenantId for MSI, CloudShell(?)
62+
[Parameter(Mandatory = false, HelpMessage = "Optional Tenant Id. Use tenant id of default context if not specified.")]
63+
public string TenantId { get; set; }
64+
65+
public override void ExecuteCmdlet()
66+
{
67+
base.ExecuteCmdlet();
68+
69+
string resourceUrlOrId;
70+
71+
if (ParameterSetName == KnownResourceNameParameterSet)
72+
{
73+
if (ResourceTypeName == null)
74+
{
75+
ResourceTypeName = SupportedResourceNames.Arm;
76+
}
77+
if (!SupportedResourceNames.ResourceNameMap.ContainsKey(ResourceTypeName))
78+
{
79+
throw new ArgumentException(Properties.Resources.InvalidResourceTypeName.FormatInvariant(ResourceTypeName), nameof(ResourceTypeName));
80+
}
81+
resourceUrlOrId = SupportedResourceNames.ResourceNameMap[ResourceTypeName];
82+
}
83+
else
84+
{
85+
resourceUrlOrId = ResourceUrl;
86+
}
87+
88+
IAzureContext context = DefaultContext;
89+
if(TenantId == null)
90+
{
91+
TenantId = context.Tenant?.Id;
92+
}
93+
94+
IAccessToken accessToken = AzureSession.Instance.AuthenticationFactory.Authenticate(
95+
context.Account,
96+
context.Environment,
97+
TenantId,
98+
null,
99+
ShowDialog.Never,
100+
null,
101+
null,
102+
resourceUrlOrId);
103+
104+
var result = new PSAccessToken()
105+
{
106+
Token = accessToken.AccessToken,
107+
TenantId = TenantId,
108+
UserId = accessToken.UserId,
109+
};
110+
result.ExpiresOn = (accessToken as MsalAccessToken)?.ExpiresOn ?? result.ExpiresOn;
111+
112+
WriteObject(result);
113+
}
114+
115+
internal class SupportedResourceNames
116+
{
117+
public const string Arm = "Arm";
118+
public const string AadGraph = "AadGraph";
119+
public const string Batch = "Batch";
120+
public const string DataLake = "DataLake";
121+
public const string KeyVault = "KeyVault";
122+
public const string ResourceManager = "ResourceManager"; //endpoint is same as Arm
123+
124+
public const string AnalysisServices = "AnalysisServices";
125+
public const string Attestation = "Attestation";
126+
public const string OperationalInsights = "OperationalInsights";
127+
public const string Synapse = "Synapse";
128+
public const string ManagedHsm = "ManagedHsm";
129+
130+
internal static Dictionary<string, string> ResourceNameMap = new Dictionary<string, string>()
131+
{
132+
{ Arm, AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId },
133+
{ AadGraph, AzureEnvironment.Endpoint.GraphEndpointResourceId },
134+
{ Batch, AzureEnvironment.Endpoint.BatchEndpointResourceId },
135+
{ DataLake, AzureEnvironment.Endpoint.DataLakeEndpointResourceId },
136+
{ KeyVault, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId },
137+
{ ResourceManager, AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId },
138+
139+
{ AnalysisServices, AzureEnvironment.ExtendedEndpoint.AnalysisServicesEndpointResourceId },
140+
{ Attestation, AzureEnvironment.ExtendedEndpoint.AzureAttestationServiceEndpointResourceId },
141+
{ OperationalInsights, AzureEnvironment.ExtendedEndpoint.OperationalInsightsEndpointResourceId },
142+
{ Synapse, AzureEnvironment.ExtendedEndpoint.AzureSynapseAnalyticsEndpointResourceId },
143+
{ ManagedHsm, AzureEnvironment.ExtendedEndpoint.ManagedHsmServiceEndpointResourceId }
144+
};
145+
}
146+
}
147+
}

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

0 commit comments

Comments
 (0)