Ova

How to create service principal in Azure using PowerShell?

Published in Azure Service Principal Creation 6 mins read

You can create a service principal in Azure using PowerShell primarily with the New-AzADServicePrincipal cmdlet. This process involves generating an identity for an application or service, which then allows it to authenticate securely with Azure AD and access Azure resources with specific permissions. When you create a service principal, you decide which type of sign-in authentication it will use, typically a client secret (password) or a certificate.

Introduction to Azure Service Principals

An Azure service principal is an identity created for use with applications, hosted services, and automated tools to access specific Azure resources. It acts as an application's identity within Azure Active Directory (Azure AD), granting it permissions to interact with your subscriptions and resources. Think of it as a user identity, but for a machine or application, ensuring secure and controlled access without requiring human credentials.

Prerequisites for Creating a Service Principal

Before you begin, ensure you have the following:

  • Azure Az PowerShell module installed: If not, install it using Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force.
  • Connected to Azure: Authenticate your PowerShell session to Azure using Connect-AzAccount.
  • Sufficient Permissions: You need permissions to create applications and service principals in Azure AD (e.g., Application Administrator, Cloud Application Administrator, or Global Administrator roles). You also need permissions to assign roles within your Azure subscription (e.g., User Access Administrator or Owner).

Creating a Service Principal with a Client Secret (Password-based)

This is the most common method, involving a client secret (password) for authentication.

Step 1: Create the Service Principal

Use the New-AzADServicePrincipal cmdlet to create the service principal and its associated Azure AD application registration. When you create a service principal, you choose its sign-in authentication type. By default, this cmdlet uses a client secret.

# Define a display name for your service principal
$servicePrincipalName = "MyWebAppServicePrincipal"

# Create the service principal
# Important: Beginning with Az PowerShell module version 7.x,
# New-AzADServicePrincipal no longer assigns the Contributor role to the service principal by default.
$servicePrincipal = New-AzADServicePrincipal -DisplayName $servicePrincipalName

# Output the Application ID and generated secret
Write-Host "Service Principal Display Name: $($servicePrincipal.DisplayName)"
Write-Host "Application ID (Client ID): $($servicePrincipal.ApplicationId)"
Write-Host "Tenant ID: $($servicePrincipal.TenantId)"
Write-Host "Client Secret (Password): $($servicePrincipal.Secret)" # Store this securely!

# You'll need the ApplicationId, TenantId, and Client Secret for connecting later.
# It is crucial to securely store the client secret as it's only shown once.

Note: The output of $servicePrincipal.Secret is the only time you'll see the generated client secret. Store it securely immediately (e.g., in Azure Key Vault).

Step 2: Assign Permissions (Role Assignment)

Since New-AzADServicePrincipal no longer assigns the Contributor role by default (as of Az PowerShell module version 7.x), you must explicitly assign the necessary permissions. Grant the least privilege required for the service principal's operations.

# Define the scope of access (e.g., subscription, resource group)
# Example: Assigning Contributor role to the entire subscription
$subscriptionId = (Get-AzContext).Subscription.Id
$roleName = "Contributor" # Choose the appropriate role, e.g., 'Reader', 'Storage Blob Data Contributor'

New-AzRoleAssignment -ApplicationId $servicePrincipal.ApplicationId -RoleDefinitionName $roleName -Scope "/subscriptions/$subscriptionId"

Write-Host "Assigned '$roleName' role to '$($servicePrincipal.DisplayName)' at subscription scope."

# Example: Assigning a role to a specific resource group
# $resourceGroupName = "MyResourceGroup"
# $resourceGroupId = (Get-AzResourceGroup -Name $resourceGroupName).Id
# New-AzRoleAssignment -ApplicationId $servicePrincipal.ApplicationId -RoleDefinitionName $roleName -Scope $resourceGroupId

Creating a Service Principal with a Certificate (Certificate-based)

Certificate-based authentication is generally more secure for production environments.

Step 1: Create or Obtain a Certificate

You need a certificate (.cer or .pem file) that will be used by the service principal. You can use a self-signed certificate for testing or obtain one from a Certificate Authority (CA) for production.

# Example: Create a self-signed certificate (for testing purposes)
$cert = New-SelfSignedCertificate -CertStoreLocation "Cert:\CurrentUser\My" `
                                  -DnsName "mycert.serviceprincipal.com" `
                                  -FriendlyName "ServicePrincipalCert" `
                                  -NotAfter (Get-Date).AddYears(1)

# Export the certificate's public key for Azure AD (without private key)
$certPath = "C:\temp\ServicePrincipalCert.cer"
Export-Certificate -Cert $cert -FilePath $certPath -Type CERT

Write-Host "Certificate created and exported to: $certPath"
Write-Host "Certificate Thumbprint: $($cert.Thumbprint)"

# Note: For production, consider using Azure Key Vault to manage certificates.

Step 2: Create the Service Principal with the Certificate

Provide the certificate thumbprint when creating the service principal.

# Define a display name for your service principal
$certServicePrincipalName = "MyCertAppServicePrincipal"
$certThumbprint = $cert.Thumbprint # Use the thumbprint from your certificate

# Create the service principal with certificate authentication
# Remember the default role assignment change for Az module v7.x+
$certServicePrincipal = New-AzADServicePrincipal -DisplayName $certServicePrincipalName `
                                                -CertThumbprint $certThumbprint

Write-Host "Service Principal Display Name: $($certServicePrincipal.DisplayName)"
Write-Host "Application ID (Client ID): $($certServicePrincipal.ApplicationId)"
Write-Host "Tenant ID: $($certServicePrincipal.TenantId)"
Write-Host "Certificate Thumbprint Used: $certThumbprint"

Step 3: Assign Permissions (Role Assignment)

Similar to client secret-based service principals, you must explicitly assign roles for certificate-based ones.

# Define the scope of access
$subscriptionId = (Get-AzContext).Subscription.Id
$roleName = "Reader" # Example: Assigning Reader role

New-AzRoleAssignment -ApplicationId $certServicePrincipal.ApplicationId -RoleDefinitionName $roleName -Scope "/subscriptions/$subscriptionId"

Write-Host "Assigned '$roleName' role to '$($certServicePrincipal.DisplayName)' at subscription scope."

Connecting to Azure Using a Service Principal

Once created and assigned permissions, you can use the service principal to authenticate.

Using Client Secret

# Using Application ID, Tenant ID, and Client Secret
Connect-AzAccount -ServicePrincipal `
                  -TenantId "YOUR_TENANT_ID" `
                  -ApplicationId "YOUR_APP_ID" `
                  -ClientSecret "YOUR_CLIENT_SECRET"

Using Certificate

# Ensure the certificate is installed in the current user's or local machine's certificate store
Connect-AzAccount -ServicePrincipal `
                  -TenantId "YOUR_TENANT_ID" `
                  -ApplicationId "YOUR_APP_ID" `
                  -CertificateThumbprint "YOUR_CERT_THUMBPRINT"

Managing Service Principals

Listing Service Principals

You can list existing service principals using Get-AzADServicePrincipal.

# Get all service principals
Get-AzADServicePrincipal

# Get a specific service principal by Application ID
Get-AzADServicePrincipal -ApplicationId "YOUR_APP_ID"

# Get a specific service principal by Display Name
Get-AzADServicePrincipal -DisplayName "MyWebAppServicePrincipal"

Deleting Service Principals

To remove a service principal, use Remove-AzADServicePrincipal. This also deletes the associated application registration.

# Get the service principal object first
$spToDelete = Get-AzADServicePrincipal -ApplicationId "YOUR_APP_ID_TO_DELETE"

# Remove the service principal
Remove-AzADServicePrincipal -ObjectId $spToDelete.Id -PassThru # -PassThru confirms deletion

Key Considerations and Best Practices

  • Least Privilege: Always follow the principle of least privilege. Grant service principals only the permissions they absolutely need, and no more.
  • Secret Management: Never hardcode client secrets in code. Use secure storage solutions like Azure Key Vault to store and retrieve secrets.
  • Certificate Rotation: Implement a robust process for rotating certificates before they expire to prevent service outages.
  • Monitoring: Monitor service principal activities using Azure AD sign-in logs and activity logs to detect anomalous behavior.
  • Audit: Regularly audit existing service principals and their assigned roles to ensure they are still necessary and have appropriate permissions.

Comparison of Authentication Methods

Feature Client Secret (Password-based) Certificate-based Authentication
Security Generally less secure; requires careful secret management. More secure; private key never leaves the client.
Complexity Simpler to set up. More complex setup (certificate generation, management).
Expiration Secrets have an expiration date (max 2 years). Certificates have an expiration date.
Management Stored securely (e.g., Key Vault), rotated regularly. Stored securely (e.g., Key Vault), rotated regularly.
Recommended Use Development, testing, non-critical applications. Production, critical applications, highly secure environments.