Skip to content

Instantly share code, notes, and snippets.

@zplume
Last active September 27, 2017 09:27
Show Gist options
  • Save zplume/5280aec3db84bd3f7eb4d7da60496eb8 to your computer and use it in GitHub Desktop.
Save zplume/5280aec3db84bd3f7eb4d7da60496eb8 to your computer and use it in GitHub Desktop.
Param(
[Parameter(Mandatory=$True)]
$AppPrincipalId,
[Parameter(Mandatory=$True)]
$TenantId,
[string]$ClientSecret
)
try
{
$ErrorActionPreference = "Stop"
[System.Guid]::Parse($AppPrincipalId) | Out-Null
[System.Guid]::Parse($TenantId) | Out-Null
if([string]::IsNullOrWhiteSpace($ClientSecret)) {
$bytes = New-Object Byte[] 32
$rand = [System.Security.Cryptography.RandomNumberGenerator]::Create()
$rand.GetBytes($bytes)
$rand.Dispose()
$newClientSecret = [System.Convert]::ToBase64String($bytes)
}
else {
$newClientSecret = $ClientSecret
}
$dtStart = [System.DateTime]::Now.AddDays(-1)
$dtEnd = $dtStart.AddYears(3)
Write-Host -f Green "`nUpdating app $AppPrincipalId in tenant $TenantId"
[System.Threading.Thread]::Sleep(1000)
Write-Host -f Gray "`nConnecting to Azure AD"
Connect-MsolService
# Recreate the service principal for instant update
Write-Host -f Gray "`nUpdating service principal"
$servicePrincipal = Get-MsolServicePrincipal -TenantId $TenantId -AppPrincipalId $AppPrincipalId
Remove-MsolServicePrincipal -TenantId $TenantId -AppPrincipalId $AppPrincipalId
New-MsolServicePrincipal -TenantId $TenantId -AppPrincipalId $AppPrincipalId -DisplayName $servicePrincipal.DisplayName -ServicePrincipalNames $servicePrincipal.ServicePrincipalNames -AccountEnabled:$true -Addresses $servicePrincipal.Addresses
# Remove the auto-generated key
$keys = @()
Get-MsolServicePrincipalCredential -TenantId $TenantId -AppPrincipalID $AppPrincipalId -ReturnKeyValues:$true | ForEach-Object {
$keys += $_.KeyId
}
Remove-MsolServicePrincipalCredential -TenantId $TenantId -AppPrincipalID $AppPrincipalId -KeyIds $keys
Write-Host -f Gray "`nCreating new service principal credentials"
New-MsolServicePrincipalCredential -TenantId $TenantId -AppPrincipalId $AppPrincipalId -Type Symmetric -Usage Sign -Value $newClientSecret -StartDate $dtStart -EndDate $dtEnd
New-MsolServicePrincipalCredential -TenantId $TenantId -AppPrincipalId $AppPrincipalId -Type Symmetric -Usage Verify -Value $newClientSecret -StartDate $dtStart -EndDate $dtEnd
New-MsolServicePrincipalCredential -TenantId $TenantId -AppPrincipalId $AppPrincipalId -Type Password -Usage Verify -Value $newClientSecret -StartDate $dtStart -EndDate $dtEnd
Write-Host -f Green "`nClient secret created:"
Write-Host "$newClientSecret`n"
}
catch
{
Write-Error $_
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment