Skip to content
Merged
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
29 changes: 29 additions & 0 deletions src/Accounts/Accounts/Accounts.format.ps1xml
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,35 @@
</TableRowEntries>
</TableControl>
</View>
<View>
<Name>Microsoft.Azure.Commands.Profile.Models.PSAccessToken</Name>
<ViewSelectedBy>
<TypeName>Microsoft.Azure.Commands.Profile.Models.PSAccessToken</TypeName>
</ViewSelectedBy>
<ListControl>
<ListEntries>
<ListEntry>
<ListItems>
<ListItem>
<PropertyName>Token</PropertyName>
</ListItem>
<ListItem>
<PropertyName>ExpiresOn</PropertyName>
</ListItem>
<ListItem>
<PropertyName>Type</PropertyName>
</ListItem>
<ListItem>
<PropertyName>TenantId</PropertyName>
</ListItem>
<ListItem>
<PropertyName>UserId</PropertyName>
</ListItem>
</ListItems>
</ListEntry>
</ListEntries>
</ListControl>
</View>
<View>
<Name>Microsoft.Azure.Commands.Profile.Models.PSAzureSubscriptionPolicy</Name>
<ViewSelectedBy>
Expand Down
2 changes: 1 addition & 1 deletion src/Accounts/Accounts/Az.Accounts.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -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 = @()
Expand Down
1 change: 1 addition & 0 deletions src/Accounts/Accounts/ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
- Additional information about change #1
-->
## Upcoming Release
* Added new cmdlet `Get-AzAccessToken`
* Fixed an issue that error happens if user profile path is inaccessible
* Fixed an issue causing Write-Object error during Connect-AzAccount [#13419]
* Added parameter "ContainerRegistryEndpointSuffix" to: `Add-AzEnvironment`, `Set-AzEnvironment`
Expand Down
30 changes: 30 additions & 0 deletions src/Accounts/Accounts/Models/PSAccessToken.cs
Original file line number Diff line number Diff line change
@@ -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";
}
}
9 changes: 9 additions & 0 deletions src/Accounts/Accounts/Properties/Resources.Designer.cs

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

3 changes: 3 additions & 0 deletions src/Accounts/Accounts/Properties/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -519,6 +519,9 @@
<data name="SuggestToUseDeviceCodeAuth" xml:space="preserve">
<value>Please run 'Connect-AzAccount -DeviceCode' if browser is not supported in this session.</value>
</data>
<data name="InvalidResourceTypeName" xml:space="preserve">
<value>The specified ResourceTypeName "{0}" is not supported, please provide a valid value. e.g. Arm, AadGraph, etc.</value>
</data>
<data name="FallbackContextSaveModeDueCacheCheckError" xml:space="preserve">
<value>INITIALIZATION: Fallback context save mode to process because of error during checking token cache persistence: {0}.</value>
</data>
Expand Down
147 changes: 147 additions & 0 deletions src/Accounts/Accounts/Token/GetAzureRmAccessToken.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
// ----------------------------------------------------------------------------------
//
// 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.Management.Automation;

using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
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
{
[Cmdlet(VerbsCommon.Get, AzureRMConstants.AzureRMPrefix + "AccessToken", DefaultParameterSetName = KnownResourceNameParameterSet)]
[OutputType(typeof(PSAccessToken))]
public class GetAzureRmAccessTokenCommand : AzureRMCmdlet
{
private const string ResourceUrlParameterSet = "ResourceUrl";
private const string KnownResourceNameParameterSet = "KnownResourceTypeName";

[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, AnalysisServices, Arm, Attestation, Batch, DataLake, KeyVault, OperationalInsights, ResourceManager, Synapse. Default value is Arm if not specified.")]
[PSArgumentCompleter(
SupportedResourceNames.AadGraph,
SupportedResourceNames.AnalysisServices,
SupportedResourceNames.Arm,
SupportedResourceNames.Attestation,
SupportedResourceNames.Batch,
SupportedResourceNames.DataLake,
SupportedResourceNames.KeyVault,
SupportedResourceNames.ManagedHsm,
SupportedResourceNames.OperationalInsights,
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; }

public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();

string resourceUrlOrId;

if (ParameterSetName == KnownResourceNameParameterSet)
{
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];
}
else
{
resourceUrlOrId = ResourceUrl;
}

IAzureContext context = DefaultContext;
if(TenantId == null)
{
TenantId = context.Tenant?.Id;
}

IAccessToken accessToken = AzureSession.Instance.AuthenticationFactory.Authenticate(
context.Account,
context.Environment,
TenantId,
null,
ShowDialog.Never,
null,
null,
resourceUrlOrId);

var result = new PSAccessToken()
{
Token = accessToken.AccessToken,
TenantId = TenantId,
UserId = accessToken.UserId,
};
result.ExpiresOn = (accessToken as MsalAccessToken)?.ExpiresOn ?? result.ExpiresOn;

WriteObject(result);
}

internal class SupportedResourceNames
{
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 AnalysisServices = "AnalysisServices";
public const string Attestation = "Attestation";
public const string OperationalInsights = "OperationalInsights";
public const string Synapse = "Synapse";
public const string ManagedHsm = "ManagedHsm";

internal static Dictionary<string, string> ResourceNameMap = new Dictionary<string, string>()
{
{ Arm, AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId },
{ AadGraph, AzureEnvironment.Endpoint.GraphEndpointResourceId },
{ Batch, AzureEnvironment.Endpoint.BatchEndpointResourceId },
{ DataLake, AzureEnvironment.Endpoint.DataLakeEndpointResourceId },
{ KeyVault, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId },
{ ResourceManager, AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId },

{ AnalysisServices, AzureEnvironment.ExtendedEndpoint.AnalysisServicesEndpointResourceId },
{ Attestation, AzureEnvironment.ExtendedEndpoint.AzureAttestationServiceEndpointResourceId },
{ OperationalInsights, AzureEnvironment.ExtendedEndpoint.OperationalInsightsEndpointResourceId },
{ Synapse, AzureEnvironment.ExtendedEndpoint.AzureSynapseAnalyticsEndpointResourceId },
{ ManagedHsm, AzureEnvironment.ExtendedEndpoint.ManagedHsmServiceEndpointResourceId }
};
}
}
}
9 changes: 3 additions & 6 deletions src/Accounts/Accounts/help/Az.Accounts.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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.

Expand Down Expand Up @@ -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.

Expand Down
Loading