Featured image of post Automating with PowerShell: Secure App Model Refresh tokens

Automating with PowerShell: Secure App Model Refresh tokens

So this is a quick one because I’ve had a talk today and noticed I never gave a fully automated way to get refresh tokens, endlessly. 🙂

When using the Secure Application Model, you only really need to go through the procedures once, after that you can get a new refresh token infinitely, without interaction.

To do that, you’ll have to use something like a keyvault, or another storage location where you store the original refresh key, we then update that key each time the script runs. You can use an Azure Function for this or just a script schedule.

Use the code below as an example to get a new refresh token, without human interaction.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
######### Secrets #########
$ApplicationId = 'ApplicationID'
$ApplicationSecret = 'ApplicationSecret' | ConvertTo-SecureString -Force -AsPlainText
$TenantID = 'TenantID'
$RefreshToken = 'LongRefreshToken'
$ExchangeRefreshToken = 'LongExchangeRefreshToken'
$UPN = "YourPrettyUpnUsedToGenerateTokens"
######### Secrets #########
$credential = New-Object System.Management.Automation.PSCredential($ApplicationId, $ApplicationSecret)

$aadGraphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes 'https://graph.windows.net/.default' -ServicePrincipal -Tenant $tenantID
$graphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes 'https://graph.microsoft.com/.default' -ServicePrincipal -Tenant $tenantID

$NewAADRefreshToken = $aadGraphToken.RefreshToken
$NewGraphToken = $graphToken.RefreshToken

You can use the $NewAADRefreshtoken and $NewGraphToken to push the latest version of the refresh token somewhere safe, and also pull from it in other scrips. And that’s it! as always, Happy PowerShelling.

All blogs are posted under AGPL3.0 unless stated otherwise
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy