Use PowerShell workflows when performance matters Why move to PowerShell 7 from Windows PowerShell?

Using PowerShell for Azure service principal authentication

With help from the Azure PowerShell module, you can avoid login prompts and automate the authentication process when using service principals on Microsoft's cloud platform.

As more organizations tap in to cloud services, it helps to have an automated way to gain access to Azure resources.

You can authenticate to Microsoft Azure with a few different methods. One way to provide credentials is through a service principal and a client secret. Common uses for service principals are to run automation tasks, such as an Azure Automation runbook that handles VM deployments. Once you have an Azure service principal authentication script, you can work it into your automated workflow.

Creating and authenticating to Azure via a service principal and client secret requires four steps:

  1. Build an Azure AD application.
  2. Create a service principal.
  3. Assign a role to the service principal.
  4. Authenticate as the service principal.

To authenticate with a service principal with Azure, you'll first need to get the Az PowerShell module by downloading it from the PowerShell Gallery with the following command:

Install-Module Az

Be sure you have a user account with rights by referring to the Required Permissions section from the Microsoft documentation site.

Azure authentication window
This Azure authentication window will open to generate the subscription ID and tenant ID for the PowerShell authentication script.

Get started with the authentication process

First, we have to authenticate the interactive way by providing our username and password using the Connect-AzAccount cmdlet. When run, the cmdlet opens an Azure login window.

After entering your Azure username and password, the window should close, and the command line should show output similar to below:


Environment           : AzureCloud
Account               : <email>
TenantId              : <tenant id>
SubscriptionId        : <subscription id>
SubscriptionName      : <subscription name>
CurrentStorageAccount :

Note both the subscription ID and tenant ID for later use. If you closed the window, use the Get-AzSubscription cmdlet to display the information again.

Build the service principal

Next, create a service principal with PowerShell, which consists of a three-step process. We need to create a new Azure AD application, create the service principal and then create a role assignment for that service principal.

First, we can create the Azure AD application using the name and Uniform Resource Identifier of our choice.

$secPassword = ConvertTo-SecureString -AsPlainText -Force -String '<our password here>'
$myApp = New-AzADApplication -DisplayName AppForServicePrincipal -IdentifierUris 'http://appforserviceprincipal' -Password $secPassword

Next, create the service principal that references the application we just created.

$sp = New-AzADServicePrincipal -ApplicationId $myApp.ApplicationId

ServicePrincipalNames : {<application id>, http://appforserviceprincipal}
ApplicationId         : <application id>
DisplayName           : AppForServicePrincipal
Id                    : <service principal id>
Type                  : ServicePrincipal

Set up the role for the service principal

Next, assign a role to the service principal. The code below attaches it to a contributor role, which gives the appropriate access in the subscription.

New-AzRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName $sp.ServicePrincipalNames[0]

RoleAssignmentId   : /subscriptions/<subscription id>/providers/Microsoft.Authorization/roleAssignments/<assignment id>
Scope              : /subscriptions/<subscription id>
DisplayName        : AppForServicePrincipal
SignInName         :
RoleDefinitionName : Contributor
RoleDefinitionId   : <id>
ObjectId           : <id>
ObjectType         : ServicePrincipal
CanDelegate        : False

Lastly, save the password for the Azure app with PowerShell. Use the following code to save the secure string password to a file:

$secPassword | ConvertFrom-SecureString | Out-File -FilePath C:\AzureAppPassword.txt

Next, set up the Azure authentication portion.

Authenticating with the Connect-AzAccount cmdlet

The Az module features a command called Connect-AzAccount that, by default, prompts for a username and password. In a script designed for automation, this doesn't work. But you can avoid this interaction by creating a PSCredential object with the Azure app ID and password and pass it over.

$azureAppId = $myApp.ApplicationId
$azureAppIdPasswordFilePath = 'C:\AzureAppPassword.txt'
$azureAppCred = (New-Object System.Management.Automation.PSCredential $azureAppId, (Get-Content -Path $azureAppIdPasswordFilePath | ConvertTo-SecureString))

Now that we have a credential for the application, we can use this along with the subscription ID and tenant ID as parameters to the Connect-AzAccount command to authenticate to Azure.

$subscriptionId = '<my subscription id>'
$tenantId = '<my tenant ID>'
Connect-AzAccount -ServicePrincipal -SubscriptionId $subscriptionId -TenantId $tenantId -Credential $azureAppCred

Account          : <id>
SubscriptionName : <name>
SubscriptionId   : <subscription id>
TenantId         : <tenant id>
Environment      : AzureCloud

Completing the Azure service principal authentication script

You should now have an Azure service principal and the PowerShell code required to authenticate with it and your client secret. To connect to Azure in the future with this service principal in PowerShell, you will now need the following code and plug in the appropriate variable values.

$azureAppId = (Get-AzADApplication -DisplayName 'AppForServicePrincipal').ApplicationId.ToString()
$azureAppIdPasswordFilePath = 'C:\AzureAppPassword.txt'
$azureAppCred = (New-Object System.Management.Automation.PSCredential $azureAppId, (Get-Content -Path $azureAppIdPasswordFilePath | ConvertTo-SecureString))
$subscriptionId = '<my subscription id>'
$tenantId = '<my tenant ID>'
Connect-AzAccount -ServicePrincipal -SubscriptionId $subscriptionId -TenantId $tenantId -Credential $azureAppCred

Next Steps

25 basic PowerShell commands for Windows administrators

Understanding Windows PowerShell function parameters

Dig Deeper on Windows Server OS and management