Skip to content

Instantly share code, notes, and snippets.

@garrytrinder
Last active May 16, 2019 10:06
Show Gist options
  • Save garrytrinder/83a7248a4655425f40ba8b0530e4260d to your computer and use it in GitHub Desktop.
Save garrytrinder/83a7248a4655425f40ba8b0530e4260d to your computer and use it in GitHub Desktop.
# Requires Connect-MsolService connection to have made before running script
Param(
[Parameter(Mandatory = $true)]
[string]$AppPrincipalId
)
<#
Get App Principal Id
#>
$app = Get-MsolServicePrincipal -All | Where-Object -FilterScript { ($_.AppPrincipalId -eq $AppPrincipalId) }
if ($null -eq $app){
throw "App Principal: $AppPrincipalId - was not found on this tenant"
}
<#
Remove old secret from AppPrincipal
#>
$keys = Get-MsolServicePrincipalCredential -AppPrincipalId $app.AppPrincipalId -ReturnKeyValues $false
Remove-MsolServicePrincipalCredential -KeyIds @($keys[0].KeyId,$keys[1].KeyId,$keys[2].KeyId) -AppPrincipalId $AppPrincipalId
<#
Generate new secret
#>
$bytes = New-Object Byte[] 32
$rand = [System.Security.Cryptography.RandomNumberGenerator]::Create()
$rand.GetBytes($bytes)
$rand.Dispose()
$newClientSecret = [System.Convert]::ToBase64String($bytes)
<#
Update App Principal with new secret
#>
# start date is set to previous day to speed up the propogation
$dtStart = (Get-Date).AddDays(-1)
# default is one year, so instead we extend it to three (maximum)
$dtEnd = $dtStart.AddYears(3)
New-MsolServicePrincipalCredential -AppPrincipalId $AppPrincipalId -Type Symmetric -Usage Sign -Value $newClientSecret -StartDate $dtStart -EndDate $dtEnd
New-MsolServicePrincipalCredential -AppPrincipalId $AppPrincipalId -Type Symmetric -Usage Verify -Value $newClientSecret -StartDate $dtStart -EndDate $dtEnd
New-MsolServicePrincipalCredential -AppPrincipalId $AppPrincipalId -Type Password -Usage Verify -Value $newClientSecret -StartDate $dtStart -EndDate $dtEnd
Write-Output $newClientSecret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment