It happened like this: I needed to recycle an access token from an existing connection to the azure management plane in order to use the AzureAD PowerShell module in an Azure Function (that.. is another story). I thought I was smart, googled hard and finally came across the following hack:
$ctx = Get-AzContext
$null = Get-AzADApplication -ApplicationId $env:APP_CLIENT_ID #This fills the token cache.
$token = $ctx.TokenCache.ReadItems() |
Where-Object Resource -eq 'https://graph.windows.net/' |
Sort-Object ExpiresOn -Descending |
Select-Object -First 1 -ExpandProperty AccessToken
That worked for some time... Then Az.Accounts 2.1.0 came along and broke my code. And not only mine: Azure/azure-powershell#13337
[Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureTokenCache] does not contain a method named 'ReadItems'
Now what happend is, that the underlying authentication library in Az.Accounts was changed and the developers decided (and rightfully so!) not to expose the TokenCache anymore.
At that point people took different paths to work around this breaking change:
- Either: They pinned the version of Az.Accounts to 1.9.5
- Or: They used .NET to tap into the existing authentication session:
$ctx = Get-AzContext
$token = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate(
$ctx.'Account',
$ctx.'Environment',
$ctx.'Tenant'.'Id',
$null,
[Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never,
$null,
'https://graph.windows.net/'
).AccessToken