azure-powershell icon indicating copy to clipboard operation
azure-powershell copied to clipboard

'az account get-access-token' equivalent in Azure PowerShell

Open TylerLeonhardt opened this issue 8 years ago • 40 comments

Right now the Azure Functions CLI relies on Azure PowerShell in order to get an access token to interact with the Azure API:

https://github.com/Azure/azure-functions-core-tools/blob/60ea24fd4408ea876882324a9505c2d43bb37726/src/Azure.Functions.Cli/Actions/AzureActions/BaseAzureAction.cs#L72-L96

I opened an issue on them to change it but they consider it by design because of how complicated it is to get an access token.

Apparently there was an attempt to get this to work in Azure PowerShell as well but unfortunately, there was no way to retrieve the access token needed.

in Azure CLI, it's simple. All you do it:

az account get-access-token

I noticed that on the context object that comes back from Get-AzContext there is a property called Account which has an AccessToken property that is not set:

PS > (Get-AzContext).Account


Id                    : xxxxxxxx
Type                  : User
Tenants               : {xxxxxxxxxxxxxxxxxxx}
AccessToken           :
Credential            :
TenantMap             : {}
CertificateThumbprint :
ExtendedProperties    : {[Subscriptions, xxxxxxxxxxxx]
                        , [Tenants, xxxxxxxxxx]}



PS > (Get-AzContext).Account.AccessToken
PS >

Can this AccessToken property be set so that a user doesn't have to rely on Azure CLI to get it?

I also tried this:

$context = Get-AzContext; $context.TokenCache.ReadItems() | ? TenantId -eq $context.TenantId | % { $_.AccessToken }

but noticed that all of my tokens in the TokenCache were already expired.

TylerLeonhardt avatar Nov 05 '18 19:11 TylerLeonhardt

@TylerLeonhardt Thanks for the report. It is actually intentional that we don't expose tokems, for a few reasons:

  • They are secret
  • They can expire, and while there are refresh tokens, it can be difficult to use one to obtain a new access token from a refresh token
  • They are an implementation detail that users shouldn't have to worry about

There are a few options to use instead:

  • Use PowerShell's TokenCache with ADAL calls to authenticate a request
  • MSI Auth

If you can tell us a bit more about how you are using the token, there ay be additional options

markcowl avatar Nov 14 '18 23:11 markcowl

The problem I am facing was that the Azure Functions CLI (func not a part of Azure CLI or Azure PowerShell) relied on the Azure CLI to obtain an access token. See related issue here: https://github.com/Azure/azure-functions-core-tools/issues/840

I don't agree that they should be relying on Azure CLI but I'm going with it... and am trying to get the same token via Az.Profile so I can rely on that if Azure CLI isn't available.

I attempted and eventually succeeded in a way to obtain an access token via Az.Profile... but with a fair bit of effort. See the PR here to the func CLI: https://github.com/Azure/azure-functions-core-tools/pull/873

Specifically the code is:

$currentAzureContext = Get-AzContext
$azureRmProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile;
$profileClient = New-Object Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient($azureRmProfile);
$profileClient.AcquireAccessToken($currentAzureContext.Subscription.TenantId).AccessToken;

TylerLeonhardt avatar Nov 15 '18 00:11 TylerLeonhardt

Seems like this is fixed, although I still don't understand the underlying scenario. Please reopen if there is a continuing issue.

markcowl avatar Nov 19 '18 05:11 markcowl

I don't think I'd consider it fixed.

Is my snippet of code something I can rely on for the future?

The underlying scenario

Some context - the func CLI aka Azure Functions Core Tools is the data plane interface with Azure Functions. It allows you to work with Azure Functions locally AND publish them to Azure.

In order to publish to Azure, it needs an access token so that it can make the necessary API calls to Azure.

Their reasoning (as described in the issue linked) is that there are a multitude of different ways to log in to Azure (with multiple environments) and the func CLI didn't want to handle authentication when the Azure CLI already does a great job at doing so.

So they relied on the Azure CLI command:

az account get-access-token

To get the token to interact with the Azure API.

I wanted them to conditionally use Azure PowerShell for users of the func CLI that only use Azure PowerShell, but getting the access token from Azure PowerShell was more than trivial (see code above).

TylerLeonhardt avatar Nov 19 '18 06:11 TylerLeonhardt

Cc dev of Functions team, @ahmelsayed

TylerLeonhardt avatar Nov 19 '18 06:11 TylerLeonhardt

Underlying scenario for me is trying to hit the Kusto REST API which requires a token created against the .kusto.windows.net resource URI. The default tokens coming thru off AzContext don't work.

tokens using get-access-token --resource 'https://.....kusto.windows.net' work, while there's no way to specify the resource in our current PS offerings when asking for access tokens.

brandonh-msft avatar Jul 23 '19 20:07 brandonh-msft

Exact same issue, except the resource in my case is https://apps.azureiotcentral.com. az account get-access-token --resource works, but I'm hoping for a PS equivalent.

samarths-msft avatar Jul 31 '19 17:07 samarths-msft

In this case, why not use the Az.Kusto module?

It is fundamentally insecure to return (and display) tokens, but would it serve your purpose if we implemented a cmdlet like 'Invoke-AzWebRequest' that could make an authenticated web request?

Also, for programmatic access (such as in the azure functions cli) there is a cross-platform MSAL extension library that provides shared access to the Token Cache - this seems like a better option that using Azure PowerShell internal libraries.

markcowl avatar Jul 31 '19 20:07 markcowl

@dcaro Two dfferent issues being discussed here:

  • Integration with the function apps cli, which I think is a priority, and we should explore with the functions team
  • Potentially another reason to support Invoke-AzWebRequest

markcowl avatar Jul 31 '19 20:07 markcowl

@markcowl thanks for your reply!

Az.Kusto works only for management operations. Unfortunately they've not yet provided any way to create tables or data mappings so I have to work w/ the REST API to make this happen which necessitates a token for their resource endpoint.

I'm not familiar with Invoke-AzWebRequest but if it would make this workaround:

# Get auth token to execute Kusto queries against the Data Explorer instance to create table & data mapping
import-module az
$context = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext
$token = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, $dexResourceUrl).AccessToken

# Call Kusto endpoint to run queries
$createTableRequestBody = @{
	csl = ".create table SampleDataTable (MessageProcessedTime: datetime, CloudProvider: string, TestRun: string, Trigger: string, Properties: dynamic)"
	db = "sampledata"
}
$createDataMappingRequestBody = @{
	csl ='.create table SampleDataTable ingestion json mapping ''DataMapping'' ''[{ "column":"MessageProcessedTime","path":"$.MessageProcessedTime","datatype":"datetime"},{"column":"CloudProvider","path":"$.CloudProvider","datatype":"string"},{"column":"TestRun","path":"$.TestRun","datatype":"string"},{"column":"Trigger","path":"$.Trigger","datatype":"string"},{"column":"Properties","path":"$.Properties","datatype":"dynamic"}]'''
	db = "sampledata"
}
$headers = @{
	Accept = "application/json"
	Authorization = "Bearer $token"
	Host = $dexResourceHost
}

Invoke-RestMethod -Method Post -Uri "$dexResourceUrl/v1/rest/mgmt" -Body (ConvertTo-Json $createTableRequestBody) -ContentType "application/json" -Headers $headers >$null

more succinct/prettier or alleviate it altogether then I'm for it 👍

brandonh-msft avatar Jul 31 '19 20:07 brandonh-msft

Regarding func integration, honestly, I don't think we should be tooling around yet another CLI that people have to install. You can already do everything func CLI does with existing PS modules / dotnet calls save for func host operations (obviously not applicable to AzPosh).

Just my .02 👛

brandonh-msft avatar Jul 31 '19 20:07 brandonh-msft

Wow. That worked for me as well.

samarths-msft avatar Jul 31 '19 21:07 samarths-msft

func similarly only needs to get the token from Az if available. It already does this thanks to @TylerLeonhardt. I think his point was that it would be nice to have a better way to achieve this through Az module than it's today.

ahmelsayed avatar Jul 31 '19 21:07 ahmelsayed

my main point is we should have parity between az cli and azposh

brandonh-msft avatar Jul 31 '19 21:07 brandonh-msft

@brandonh-msft we are working on getting the parity between the az cli and Azure PowerShell but it will take a while to get there.

dcaro avatar Jul 31 '19 22:07 dcaro

I've just run into a need for this too, for an API not exposed by either Azure PowerShell or az.

While I understand the reasoning for not exposing a way to get a token, there are a few reasons I can see to do it:

  • The az CLI already has this capability, so this is a parity question
  • There is a workaround to get this in plaintext today with a few lines of PowerShell, so the security currently is obscurity. What's more, az does not seem to have applied the same security reasoning
  • PowerShell offers securestring, so official support could possibly offer a (small) improvement over the current solution
  • Using PowerShell to build more PowerShell commands to extend Azure API support is a prime usecase for PowerShell users (they're used to scripting around holes). Without token support, the two speeds of API access are "supported by Azure PowerShell" and "inaccessible" (with the latter meaning that they'll just install az like AzF recommends).

While I think Invoke-AzRestMethod has some merits, Invoke-RestMethod is quite a complex cmdlet and PowerShell users are going to expect Invoke-AzRestMethod to work exactly the same. Moreover, there are security pitfalls within an Invoke-RestMethod implementation, and the existing one is continuously audited and patched.

rjmholt avatar Nov 08 '19 17:11 rjmholt

So, there are other far more visible use cases for wanting a get-access-token equivalent in the Az powershell module. Only yesterday I was figuring out how to publish an azure sql dacpac in an azure devops pipeline without using a username/password. I needed an access token representing the service connection between devops and azure cloud (it's essentially a service principal in AAD), and I had to split it into two tasks: The first to get the token and put it into a pipeline variable, and the second to publish the dacpac with sqlpackage /accessToken parameter. Behold how opaque the script is to get the token into a pipeline variable:

FOR /F "tokens=* USEBACKQ" %%F IN (`az account get-access-token --resource=https://database.windows.net/ --query accessToken`) DO (SET var=%%F)
echo ##vso[task.setvariable variable=sqlToken;]%var%

Unless you're a comparative dinosaur (like me) with a serious masochistic streak for 90s-era batch, you're not going to figure that out in a hurry. Remember, the azure-cli devops task is locked to cmd, and the az powershell devops task is locked to powershell: I cannot mix the two, as the task only authenticates for the base platform (e.g. az login or connect-azaccount).

I'd much rather see:

write-host ("##vso[task.setvariable variable=sqlToken;](Get-AzAccessToken -Resource https://database.windows.net/)")

or even better:

$token = get-azaccesstoken -resource ...
sqlpackage ... /accessToken:$token

So, needing an access token is not that odd of an ask, and using cmd batch is extremely painful and utterly obtuse.

/cc @markcowl

oising avatar Dec 19 '19 14:12 oising

Another thing in favor of adding a command to access the token: All the known workarounds to getting it after all break in Constrained Language Mode (Which will likely be enabled in environments that are conscious of PowerShell Threats).

As for the security concerns:

  • You are using default authentication libraries. Any malicious actor that can run code as the current user can access it, there's not even any obscurity involved here.
  • It's already quite possible to do harm with the default commands
  • It does not provide capabilities a motivated developer cannot build himself/herself by using officially published APIs.

Regarding issues with Token handling:

Get-AzToken (or whatever it ends up being called) could return a complex object, containing the token as a property, but also meta information about when it will expire. The command could also handle the automatic token refresh. Heck, the read accessor for the token on the object could implement it!

FriedrichWeinmann avatar May 27 '20 05:05 FriedrichWeinmann

We are releasing new cmdlet to support REST HTTP call. But currently, we only support resource management endpoint. Please share your thought and we hope to continue improving it.

dingmeng-xue avatar Jul 13 '20 13:07 dingmeng-xue

@dingmeng-xue I don't believe that solves any of reasons this thread was opened or the comments/upvotes since:

  1. Functions publishing
  2. Kusto query publishing
  3. Azure IoT
  4. Azure SQL
  5. Graph
  6. VS CodeSpaces

IMO we should solve for these first unless there's another issue somewhere else (w/ as much activity on it) requesting az-token access to the management plane.

brandonh-msft avatar Jul 13 '20 14:07 brandonh-msft