Azure Service Principal using Password Authentication

If you wanted to ever setup a service account to use for Azure administration that uses a password for authentication, setup a Service Principal in AAD. Use this to use for things like Azure automation or any of those other Azure PowerShell admin scripts you have.

See my other post on how to setup an Azure AD Service Principal using certificate based authentication instead.


### Written with Azure PowerShell Module version 4.4.1
# Fill in the below variables
$SPDisplayName = 'User Account SP'
$SPPassword = 'password' # Password is required
$ResourceGroup = '' # Leave blank for subscription scope as to where to apply the SP role to
$Role = 'Contributor' # Could also be 'Owner'
Login-AzureRmAccount
### Choose Subscription
$subscription = Get-AzureRmSubscription | Out-GridView -Title "Select the Azure subscription that you want to use …" -PassThru
Select-AzureRmSubscription -SubscriptionId $subscription.id
$SubscriptionId = $subscription.id
#region Setup the Service Pricipal in Azure AD
if ($ResourceGroup -eq '')
{
$Scope = "/subscriptions/" + $SubscriptionId
}
else
{
$Scope = (Get-AzureRmResourceGroup -Name $ResourceGroup -ErrorAction Stop).ResourceId
}
# Create Service Principal for the AD app – This step skips New-AzureRmADApplication but creates an Azure AD application
$ServicePrincipal = New-AzureRmADServicePrincipal -DisplayName $SPDisplayName -Password $SPPassword
Get-AzureRmADServicePrincipal -ObjectId $ServicePrincipal.Id
$NewRole = $null
$Retries = 0;
While ($NewRole -eq $null -and $Retries -le 30)
{
# Sleep here for a few seconds to allow the service principal application to become active (should only take a couple of seconds normally)
Sleep 1
New-AzureRMRoleAssignment -RoleDefinitionName $Role -ServicePrincipalName $ServicePrincipal.ApplicationId.Guid -Scope $Scope -ErrorAction SilentlyContinue
$NewRole = Get-AzureRMRoleAssignment -ObjectId $ServicePrincipal.Id -ErrorAction SilentlyContinue
$Retries++;
}
#endregion
#region Remove the Serivice Principal – ONLY IF YOU REALLY NEED TO
#Remove-AzureRmADServicePrincipal -ObjectId $ServicePrincipal.Id -Force
Get-AzureRmADApplication | ? {$_.ApplicationId -eq $ServicePrincipal.ApplicationId.Guid} | Remove-AzureRmADApplication -Force
#endregion
#region TEST Logon to Azure & choose the Azure subscription using an SPN
### Test log into Azure with the new SP account
$secpasswd = ConvertTo-SecureString $SPPassword -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential ($ServicePrincipal.ApplicationId, $secpasswd)
$TenantId = $subscription.TenantId
Login-AzureRmAccount -Credential $cred -ServicePrincipal -TenantId $TenantId
$Subscription = (Get-AzureRmSubscription | Out-GridView -Title "Choose a Source & Target Subscription …" -PassThru)
Select-AzureRmSubscription -SubscriptionId $Subscription.Id
#endregion

Leave a comment