Skip to content

Instantly share code, notes, and snippets.

@manualbashing
Last active November 20, 2020 16:13
Show Gist options
  • Save manualbashing/574185d476cef2cf6297646c6edc6b85 to your computer and use it in GitHub Desktop.
Save manualbashing/574185d476cef2cf6297646c6edc6b85 to your computer and use it in GitHub Desktop.
How a breaking change in Az.Accounts broke my code

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:

  1. Either: They pinned the version of Az.Accounts to 1.9.5
  2. 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
published: false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment