Use PowerShell workflows when performance matters How to secure passwords with PowerShell
X

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 an IT administrator managing cloud services such as Microsoft 365 or Azure, you might need to automate specific tasks using PowerShell. Microsoft provides many authentication approaches and methods for connecting to their services:

  1. Interactive login. This method involves signing in with an Azure Active Directory (AD) account through the PowerShell prompt. This method is best suited for ad hoc tasks, requiring users to provide their credentials each time they authenticate.
  2. Managed identity. This feature lets a resource authenticate to Azure AD without requiring explicit credentials. This method is best suited for scenarios where a resource must access another resource securely, such as when a VM must access a storage account.
  3. Device authentication. This method involves authenticating with a code provided through the Azure portal. You use it when a user must authenticate from a device that doesn't support modern authentication protocols.

Though these options work well, you should use the service principal approach if you want to automate using code such as PowerShell.

You use service principals to access Azure resources specifically for automation scenarios. You would use Azure service principals with PowerShell for various scenarios:

  • Automated tasks and scripts.
  • Continuous integration and deployment.
  • Access control and security.
  • Resource access from external applications.
  • Provisioning and management of Azure resources.

You can create service principals either within the Azure portal or using PowerShell. The most straightforward approach is the Azure portal, which requires these steps:

  • Log in to the Azure portal.
  • Navigate to Azure AD, then select App registrations.
  • Click New registration to register a new application.
  • Enter the application's name, then select the appropriate account type.
Azure AD supported account type selection
When setting up service principles in Azure AD, you must select which accounts will have access.
  • Set the redirect URI, which specifies the endpoint to which Azure AD should redirect users after they have authenticated.
  • Once you have registered the application, you can create a service principal by selecting Certificates & secrets from the left-hand menu and then clicking New client secret.
  • Enter a name for the new secret, select an expiration date and then click Add. Copy and save the new secret.
  • Finally, you can retrieve the application's client ID, tenant ID and client secret values, which you use to authenticate to Azure using PowerShell.

If you choose to use PowerShell to create the service principal, you can use the PowerShell module Az. You can import the module from the PowerShell Gallery. The creation and authentication require three core steps:

  1. Create a service principal.
  2. Assign a role to the service principal.
  3. Authenticate as the service principal.

Get started with the authentication process

You must first install and import the module.

# Install and import the 'Az' Module
Install-Module Az
Import-Module Az

With the correct module(s) installed, you must authenticate using the interactive approach to Azure.

# Authenticate to Azure
Connect-AzAccount

The authentication will require entering your username and password and passing other security checks. Once authenticated, you can execute other commands within that security context, so you must have the proper permissions assigned. For the Az module, you must assign permission to the account you use. Take note of the tenant details if they display after authentication; if not, you can execute Get-AzSubscription or Get-AzContext.

Azure account tenant ID
Azure subscription and tenant IDs

Build the service principal

After authenticating, you can start creating the service principal, which consists of the steps you complete using the Azure portal browser.

# Creating the Service principal
$startDate = Get-Date
$endDate = (Get-Date).AddDays(100)
$name = "App-Az"
$app = New-AzADServicePrincipal -DisplayName $name

Update-AzADApplication `
-ApplicationId $app.AppId `
-IdentifierUris "api://app-az" `
-ReplyUrls "https://localhost"

$creds = [Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.MicrosoftGraphPasswordCredential]@{
StartDateTime = $startDate
EndDateTime = $endDate
}

$spCreds = New-AzADAppCredential `
-ApplicationId $app.AppId `
-PasswordCredentials $creds

You may save the password for later use. You can retrieve the SecretText property and store it in a flat file or somewhere like a credential database. To save the secret in a flat file, you can use the Out-File command, passing in the required value.

$spCreds.SecretText | Out-File "C:\Temp\Azure.txt"

Configure the service principal role

Service principal roles define the level of access that the principal has to Azure resources. There are four built-in service principal roles in Azure:

  1. Owner. Full access to all resources and can manage access to those resources.
  2. Contributor. Full access to all resources but cannot grant access to others.
  3. Reader. View-only access to all resources.
  4. User access administrator. Full access to manage user access to Azure resources.

To assign the role to the service principal using PowerShell, use the following code depending on the selected module.

# Set the service principal role
$roleParam = @{
RoleDefinitionName = "Contributor"
PrincipalId = $app.Id
}
New-AzRoleAssignment @roleParam
Assigned service principal role in Azure
Azure role assignment name and ID

Connecting to Azure using the service principal

To connect to Azure using the new service principal in PowerShell, you create a new PSCredential object comprised of the values you retrieved earlier.

$clientSecret = $spCreds.SecretText | ConvertTo-SecureString -AsPlainText -Force

If you stored the secret using the flat file approach, you must retrieve the file and the stored value.

$clientSecret = Get-Content "C:\Temp\Azure.txt" | ConvertTo-SecureString -AsPlainText -Force

With the required secret plus the tenant ID, you can connect using Connect-AzAccount and the -ServicePrincipal property.

$connectCreds = New-Object -TypeName System.Management.Automation.PSCredential `
-ArgumentList $app.AppId, $clientSecret
Connect-AzAccount -ServicePrincipal -Credential $connectCreds -Tenant $tenant.Tenant.Id

As you can see, connecting to Azure using a service principal provides better security, enables automation, and reduces the need for user credentials. It allows scripts and applications to authenticate and authorize without exposing user credentials, ensuring that sensitive data is protected.

Next Steps

25 basic PowerShell commands for Windows administrators

Understanding Windows PowerShell function parameters

Reveal Windows file server permissions with PowerShell's help

Dig Deeper on Windows Server OS and management