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

Enable a way to get an access token for an authenticated account

Open tillig opened this issue 10 years ago • 27 comments

I believe I'm running into the same (or similar) issue as seen in #1164.

I'm trying to automate the use of Azure Key Vault keys through PowerShell but there aren't currently cmdlets for encrypting/decrypting values. I can call the REST API operations but I need an access token. Given the user is already authenticated, re-authenticating just for that seems like an added unnecessary interaction.

I looked at the commands available for Invoke-AzureRmResourceAction but there is no command for encrypting or decrypting using Key Vault.

I also noticed that the Account.AccessToken is null when I do Get-AzureRmContext so I can't get the token from there, either.

Having a generic Invoke-AzureRestMethod as suggested in #1164 would get me around the challenge of not having PowerShell cmdlets for all the operations - I could write them myself.

tillig avatar Jun 22 '16 16:06 tillig

Closing as duplicate of #1164

markcowl avatar Jun 22 '16 19:06 markcowl

Are you planning on re-opening #1164? The last note in there indicates that a new issue should be filed if the challenge comes up again, which is why I opened what's effectively a duplicate.

If not, is there a workaround? Or was it decided this isn't an interesting scenario to support?

tillig avatar Jun 22 '16 19:06 tillig

@tillig That's what I get for not rereading the old issue

markcowl avatar Jun 24 '16 00:06 markcowl

I would like to be able to obtain an access token for "graph.microsoft.com", then then make rest calls to it. Purpose is to read all application info, including key expiration date and owner which is not returned by Get-AzureRmADApplication.

jnxxx avatar Jul 14 '16 13:07 jnxxx

@tillig @jnxxx If you need access in the same AppDomain (read PowerShell session) then you can use [Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache]::DefaultShared which will contain the tokens you need. If you need access in a different AppDomain, then you can use TokenCahce.Deserialize with the data from PowerShell's TokenCache, which you can get this way:

$cache = [Microsoft.WindowsAzure.Commands.Common.AzureRMProfileProvider]::Instance.Profile.Context.TokenCache

markcowl avatar Aug 08 '16 18:08 markcowl

So, to verify, I'd be looking at a workaround like this?

$tenantId = (Get-AzureRmSubscription -SubscriptionId 'subscription-id-guid-here').TenantId
$cache = [Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache]::DefaultShared
$token = $cache.ReadItems() | Where-Object { $_.TenantId -eq $tenantId }
# $token.AccessToken is the token to use for REST ops

tillig avatar Aug 08 '16 18:08 tillig

Hi.

I found a workarround to get an access token with PowerShell, user name and password: https://www.sepago.com/blog/2016/08/09/create-a-bearer-access-token-for-Azure-REST-silent-user-password

MarcelMeurer avatar Aug 10 '16 08:08 MarcelMeurer

I am using this code to get my token in my scripts, Works really great - ref. https://blogs.technet.microsoft.com/paulomarques/2016/04/05/working-with-azure-rest-apis-from-powershell-getting-page-and-block-blob-information-from-arm-based-storage-account-sample-script/


function GetAuthToken {
   param([Parameter(Mandatory=$true)]$ApiEndpointUri, [Parameter(Mandatory=$true)]$AADTenant)

   $adal = "${env:ProgramFiles(x86)}\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Services\" + `
"Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
   $adalforms = "${env:ProgramFiles(x86)}\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Services\" + `
"Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll"

   [System.Reflection.Assembly]::LoadFrom($adal) | Out-Null
   [System.Reflection.Assembly]::LoadFrom($adalforms) | Out-Null

   $clientId = "1950a258-227b-4e31-a9cf-717495945fc2"
   $redirectUri = "urn:ietf:wg:oauth:2.0:oob"
   $authorityUri = “https://login.windows.net/$aadTenant”

   $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authorityUri

   $authResult = $authContext.AcquireToken($ApiEndpointUri, $clientId,$redirectUri, "Auto")

return $authResult
} 

Token can then be embedded in the header

$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", $token.CreateAuthorizationHeader())

@jnxxx just change $ApiEndpointUri = "https://management.azure.com/" to $ApiEndpointUri = "https://graph.windows.net"

initparam avatar Aug 23 '16 18:08 initparam

@MarcelMeurer @initparam In the same appdomain, code like this will automatically use the TokenCache provided by PowerShell, and can use the same tokens, if you use the ClientId for PowerShell, and the appropriate user id and tenantid when retrieving the tokens.

I would advise calling AcquireTokenSilent for each request - this will just grab the access token from the cache, or automatically get a new access token using the refresh token in the cache if the token has expired.

@tillig No, more like what @MarcelMeurer is doing. If you pass the TokenCache in when creating the AuthenticationContext, then, if you use the same values as powershell (client id, user id, tenant id) you will get the same tokens that powwrshell woudl have. You do not have direct access to tokens from the cache, which is one of the reasons we don't return them.

markcowl avatar Sep 06 '16 06:09 markcowl

OK, now I'm confused. Up here @markcowl you mentioned...

If you need access in the same AppDomain (read PowerShell session) then you can use [Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache]::DefaultShared which will contain the tokens you need.

My follow-up comment uses the shared cache, but apparently not in the prescribed way. However, the example you point to by @MarcelMeurer just gets a token fresh using a REST call - it doesn't use any authentication context or cache or anything.

Perhaps you could provide a short but complete code example explaining what you mean to help disambiguate? If me getting the token out of the token cache isn't correct, how do you correctly use the cache?

tillig avatar Sep 06 '16 15:09 tillig

Sorry, should have said @initparam is doing. When initializing the AuthenticationContext, you can pass in a token cache, or it will automatically use the DefaultSHared TokenCache in the current AppDomain.

markcowl avatar Sep 27 '16 23:09 markcowl

The following worked for me:

function Get-AccessToken($tenantId) {
    $cache = [Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache]::DefaultShared
    $cacheItem = $cache.ReadItems() | Where-Object { $_.TenantId -eq $tenantId } | Select-Object -First 1
    return $cacheItem.AccessToken
}

Main issue I have is that I can't seem to use that token for a call to the Azure AD Graph API unless Iset the version to 1.42-previewInternal, but there is a bug in that version of the API if you use a service principal :P

robdmoore avatar Mar 12 '17 07:03 robdmoore

Just to be explicit for the noob, here's how to get a token to make a Invoke-RestMethod call to list all the resourceGroups (you'd normally use Get-AzureRMResourceGroup, but just showing a simple example in this case:


Function Get-AccessToken($tenantId) {
    $cache = [Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache]::DefaultShared
    $cacheItem = $cache.ReadItems() | Where-Object { $_.TenantId -eq $tenantId } | Select-Object -First 1
    return $cacheItem.AccessToken
}

$tentantID = (Get-AzureRmSubscription -SubscriptionName Dev).tenantID
$SubscriptionID = (Get-AzureRmSubscription -SubscriptionName Dev).SubscriptionId
$token = Get-AccessToken $tentantID

$requestHeader = @{
  "Authorization" = "Bearer " + $token
  "Content-Type" = "application/json"
}

$ApiEndpoint = 'management.usgovcloudapi.net'
$Uri = "https://$ApiEndpoint/subscriptions/$SubscriptionID/resourceGroups?api-version=2016-09-01"
$Result = (Invoke-RestMethod -Method Get -Headers $requestheader -Uri $Uri

pburkholder avatar Apr 21 '17 17:04 pburkholder

@pburkholder @markcowl How does the above respond when the access token expires? With AcquireTokenSilent I'd a new token behind the scenes, but I cannot determine how to access the AuthenticationContext of the already authenticated session in order to make the call to AcquireTokenSilent.

jimoneil avatar Jun 03 '17 01:06 jimoneil

For some reason, I was not able to obtain an access token by using:

$cache = [Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache]::DefaultShared

I was able to get it by doing this:

Add-AzureRmAccount
$context = Get-AzureRmContext
$cache = $context.TokenCache
$cacheItem.AccessToken

However, I am trying to use the token to authenticate with the AzureAD PowerShell module's Connect-AzureAD cmdlet: Connect-AzureAD -AadAccessToken $cacheItem.AccessToken -AccountId "<account-id>" -TenantId $tenantId

At first, this appears to work because the method returns without error, but when I make a subsequent call to another AzureAD cmdlet to verify that I've successfully authenticated: Get-AzureADTenantDetail

I get the following error:

Get-AzureADTenantDetail : Error occurred while executing GetTenantDetails Code: Authentication_ExpiredToken Message: Your access token has expired. Please renew it before submitting the request.

I realize this may be something I need to raise with the AzureAD PowerShell module team, but wanted to verify with someone here that I haven't gone astray by switching from:

$cache = [Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache]::DefaultShared

to

$context = Get-AzureRmContext $cache = $context.TokenCache

Are the tokens between the AzureRM and AzureAD modules compatible?

pauldalyii avatar Aug 09 '17 22:08 pauldalyii

@pauldalyii they shouldn't be because you are authenticating to a completely different endpoint. That being said, I would love so see a way to use AzureRM session to auth to AzureAD. Anyone?

4c74356b41 avatar Aug 10 '17 12:08 4c74356b41

Sharing sessions would be awesome, but ultimately I'd just like the AzureAD module to merge with AzureRm. There's a weird overlap of AD features and the AD module is much further ahead.

Until that day comes, I'd like the Azure PowerShell task in VSTS to load both the AzureRm and AzureAD modules, not just AzureRM. I've got another issue regarding this here:

https://github.com/Microsoft/vsts-tasks/issues/4830

pauldalyii avatar Aug 25 '17 16:08 pauldalyii

Has anyone read a token with c#. So, login to powershell Save azure RM context Run an exe to read the json context and get a bearer token within c# Call azure APIs

mikeblakeuk avatar Nov 28 '17 19:11 mikeblakeuk

Closing in favor of https://github.com/Azure/azure-powershell/issues/3806

maddieclayton avatar Dec 05 '17 23:12 maddieclayton

Although this is closed, @pauldalyii got very close. When I played with this, I noticed a collection of tokens. All but one had a resource property pointing to management.core.windows.net. But one of them was pointing to graph.windows.net. That token, it turns out, works great.

$context = Get-AzureRmContext
$cache = $context.TokenCache
$cacheItem = $cache.ReadItems()

$token = ($cacheItem | where { $_.Resource -eq "https://graph.windows.net/" }).accessToken

$aad = Connect-AzureAD -AadAccessToken $token -AccountId $context.Account.Id -TenantId $context.Tenant.Id

#test
Get-AzureADApplication

bretthackermsft avatar Mar 07 '18 08:03 bretthackermsft