This week I had to repeat the process of creating a Service Principal in order to use the Microsoft.Azure.Management.Fluent lib with .NET Core so I decided it was time to script the process. With the following script you can Create a Service Principal and write required parameters to a .azureauth file.

You’ll need the AzureRM PowerShell module installed:

1Install-Module AzureRM 

Here is the code:

  1<#
  2    .SYNOPSIS
  3        New-ServicePrincipalAsReader is a PowerShell script to create a Read only Service Principal in Azure.
  4        The script will write a file ([subscriptionName].azureauth) with all the parameters needed to use the Microsoft.Azure.Management.Fluent lib.
  5        SECURITY: The file [subscriptionName].azureauth will contain the key for the  Service Principal.
  6
  7    .DESCRIPTION
  8        New-ServicePrincipalAsReader is a PowerShell script to create a Read only Service Principal in Azure.
  9        The script will write a file ([subscriptionName].azureauth) with all the parameters needed to use the Microsoft.Azure.Management.Fluent lib.
 10        SECURITY: The file [subscriptionName].azureauth will contain the key for the  Service Principal.
 11        
 12    .PARAMETER subscriptionName
 13        The name of the subscription to connect.
 14    
 15    .PARAMETER servicePrincipalName
 16        The name of of the Service Principal. Default value is: logReader
 17    
 18    .NOTES 
 19        AUTHOR: Carlos Mendible 
 20        LASTEDIT: August 02, 2017 
 21#>
 22Param(
 23    [Parameter(Mandatory = $true)]
 24    [string]$subscriptionName,
 25    [Parameter(Mandatory = $false)]
 26    [string]$servicePrincipalName = "logReader"
 27)
 28
 29# Creates an AesKey.
 30function Create-AesKey() {
 31    $aesManaged = New-Object "System.Security.Cryptography.AesManaged"
 32    $aesManaged.Mode = [System.Security.Cryptography.CipherMode]::CBC
 33    $aesManaged.Padding = [System.Security.Cryptography.PaddingMode]::Zeros
 34    $aesManaged.BlockSize = 128
 35    $aesManaged.KeySize = 256
 36
 37    $aesManaged.GenerateKey()
 38    [System.Convert]::ToBase64String($aesManaged.Key)
 39}
 40
 41# Create a Service Principal as subscription Reader.
 42# Resulting file is compatible with the Microsoft.Azure.Management.Fluent lib.
 43# SECURITY ALERT: Be careful with the file and its contents 
 44function New-ServicePrincipalAsReader($subscriptionName, $applicationName) {
 45    # Login to Azure
 46    Add-AzureRmAccount
 47
 48    # Select the subscription
 49    Write-Host "Selecting subscription '$subscriptionName'";
 50    $subscriptionId = (Get-AzureRmSubscription -SubscriptionName $subscriptionName).Id
 51    Set-AzureRmContext -SubscriptionId $subscriptionId;
 52
 53    # Get the Tenant Id
 54    $tenantId = (Get-AzureRmContext).Tenant.Id
 55
 56    # Create an AD Application
 57    Write-Host "Creating the AD Application"
 58    $application = New-AzureRmADApplication `
 59        -DisplayName $applicationName `
 60        -HomePage "http://$applicationName" `
 61        -IdentifierUris "http://$applicationName"
 62
 63    # Create the Key need to authenticate with this Application
 64    $keyValue = Create-AesKey
 65    $startDate = Get-Date
 66    $endDate = $startDate.AddYears(1)
 67
 68    # Add a key to the Application
 69    Write-Host "Creating the AD Application Credential"
 70    New-AzureRmADAppCredential `
 71        -ApplicationId $application.ApplicationId `
 72        -Password $keyValue `
 73        -StartDate $startDate `
 74        -EndDate $endDate
 75
 76    # Create the service principal
 77    Write-Host "Creating the Service Principal"
 78    $servicePrincipal = New-AzureRmADServicePrincipal -ApplicationId $application.ApplicationId
 79    Get-AzureRmADServicePrincipal -ObjectId $servicePrincipal.Id 
 80
 81    # Make the service principal Reader
 82    Write-Host "Set the Principal as Reader"
 83    $ownerRole = $null
 84    $retries = 0;
 85    While ($ownerRole -eq $null -and $retries -le 6) {
 86        # Sleep here for a few seconds to allow the service principal application to become active 
 87        # (should only take a couple of seconds normally)
 88        Start-Sleep 15
 89
 90        New-AzureRmRoleAssignment `
 91            -RoleDefinitionName Reader `
 92            -ServicePrincipalName $application.ApplicationId `
 93            -ErrorAction SilentlyContinue
 94        
 95        $ownerRole = Get-AzureRMRoleAssignment `
 96            -ServicePrincipalName $application.ApplicationId `
 97            -ErrorAction SilentlyContinue
 98    
 99        $retries++;
100    }
101    
102    # Write the Authentication data to a file. Please be careful with where you save this file!!!
103    $filePath = (Get-Location).Path + "\$servicePrincipalName.azureauth"
104    Add-Content $filePath "subscription=$subscriptionId"
105    Add-Content $filePath "client=$($application.ApplicationId)"
106    Add-Content $filePath "tenant=$tenantId"
107    Add-Content $filePath "key=$keyValue"
108    Add-Content $filePath "managementURI=https\://management.core.windows.net/"
109    Add-Content $filePath "baseURL=https\://management.azure.com/"
110    Add-Content $filePath "authURL=https\://login.windows.net/"
111    Add-Content $filePath "https\://graph.windows.net/"
112}
113
114New-ServicePrincipalAsReader `
115    -subscriptionName $subscriptionName `
116    -applicationName $servicePrincipalName

You can download the script from the Technet Script Gallery or collaborate here.

Hope it helps!