Renew an expiring Client Secret in SharePoint Online



This is a quick PowerShell script for renewing a client secret in SharePoint Online. For more info you can read the excellent Microsoft article here.
You have to have Microsoft Azure Active Directory Module to run it. Follow the instructions under Step 1 in the Microsoft article here:
The script is called by passing a Username, Password and the App Principal Id:
.\Client_Secret_Renew.ps1 -User "user@tenant.com" -Password "Password" -clientId "611deb09-458b-48c3-a31f-040cffdc61v2"

Here’s the script:
params([string]$User, [string]$Password, [string]$clientId)

$msolcred = New-Object System.Management.Automation.PsCredential($User,$Password)

####Connect MSOL
connect-msolservice -credential $msolcred

####Get Current Keys
$keyIDs = @()
$keys = Get-MsolServicePrincipalCredential -AppPrincipalId $clientId

$keyIDs = $keys.KeyId

####Remove Current
Remove-MsolServicePrincipalCredential -KeyIds @($keyIDs[0].tostring(),$keyIDs[1].tostring(),$keyIDs[2].tostring()) -AppPrincipalId $clientId

####Generate Random
$bytes = New-Object Byte[] 32
$rand = [System.Security.Cryptography.RandomNumberGenerator]::Create()
$rand.GetBytes($bytes)
$rand.Dispose()

####Create new client secret
$newClientSecret = [System.Convert]::ToBase64String($bytes)

####Start and End Date.
$dtStart = [System.DateTime]::Now
$dtStart = $dtStart.AddDays(-3)

$dtEnd = $dtStart.AddYears(3)

####Apply
New-MsolServicePrincipalCredential -AppPrincipalId $clientId -Type Symmetric -Usage Sign -Value $newClientSecret -StartDate $dtStart  –EndDate $dtEnd
New-MsolServicePrincipalCredential -AppPrincipalId $clientId -Type Symmetric -Usage Verify -Value $newClientSecret   -StartDate $dtStart  –EndDate $dtEnd
New-MsolServicePrincipalCredential -AppPrincipalId $clientId -Type Password -Usage Verify -Value $newClientSecret   -StartDate $dtStart  –EndDate $dtEnd

Write-Host "New Client Secret:"
Write-Host $newClientSecret

Comments