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.
######### 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.
I’m trying to run Get-IntuneApplePushNotificationCertificate (in a scheduled task across multiple tenants) but when I Connect-MSGraph I get ‘Access from personal devices is not allowed’.
I can’t domain join the machine since it’s multiple tenants. The tenant giving issues is Secuity Defaults and I don’t want to turn it off. Any suggestions?