I developed a PowerShell script that periodically updates an Azure Table tied to a storage account once a specific action completes. I am using the REST API for this since I am running this script as an automation workbook and performing actions via its managed identity.
I am retrieving a token via the traditional Get-AzAccessToken command, and derives the expiration time from it to auto-request a new token once 90% of the time elapsed via an event-based timer.
Those tokens are set to expire every hour, however, the event is not fired because the token actually expires every 15 minutes (script fails with HTTP 403 and spits an InvalidHeaderValue error).
I saw some posts about the minimum API version required and even tried to set it to the latest version available or play with older ones, as recommended by MS, to see if this would fix my issue, however it persists.
For the time-being, I solved it by trapping the 403 status and renew it on this basis (I use PSCore 7, so I can benefit from the -SkipHttpErrorCheck option from Invoke-RestMethod) – But is it the only way?
`function global:Update-AzToken {
[CmdletBinding()]
param()
begin {
$script:htAzTableHeaders = @{
'Accept' = 'application/json;odata=nometadata'
'x-ms-version' = '2021-02-12'
'x-ms-date' = [DateTime]::UtcNow.ToString('R')
}
}
process {
try {
Write-Output ">> Getting new Azure Access token..." | Out-Host
$script:oRefreshAzAccessTokenTimer.Stop()
$oAzStorageToken = Get-AzAccessToken -ResourceTypeName Storage
$script:htAzTableHeaders += @{'Authorization' = "$($oAzStorageToken.Type) $($oAzStorageToken.Token)"}
$iExpirationSeconds = (New-TimeSpan -Start ([DateTime]::UtcNow) -End $oAzStorageToken.ExpiresOn.UtcDateTime).TotalSeconds
# Reset refresh timer (in milliseconds) with new expiration values
$script:oRefreshAzAccessTokenTimer.Interval = $iExpirationSeconds * 1000 * 0.9 # Trigger refresh once 90% of expiration seconds has been reached
$script:oRefreshAzAccessTokenTimer.Start()
Write-Output ">> Azure Access token obtained." | Out-Host
} catch {
ErrorExit
} # End try/catch
} # End process
}`