How to Create a Service Principal in Azure Cloud

What is Service Principal?

Azure Service Principal is a mechanism used to authenticate with cloud resources and services. The Service principal which present in the Active directory service can be used to automate the authentication process. The SP access can be restricted with the help of the role assigned to it.

The service principle can be created from the Azure cloud portal and from the Powershell core. In this document, I will demonstrate the steps from the portal with a password and certificate-based authentication.

 

Create Service Principal from the Azure portal

To create a service principal from the Azure portal login to your Azure cloud account and follow the below steps.

  • Login to the cloud account
  • Go to Azure active directory service (Search service name in the search bar)
  • Select App Registration from the left side panel and click on New Registration.

 

 

  •  Give a name for the App, I have given “App-SP” and selected account type as Single Tenant (Can be used only this organization). Click the “Register” button to create the Application. On the overview of the application, you can see Application ID, Tenant ID, and Object ID.
  • Add a role for the newly created Service Principal, then only it can access the resources. Go to all Subscriptions from the home page.
  • Select your subscription which you want to add the rule. If your subscription is not listed select “Global subscription filter”.
  • Click Access control (IAM) from the left side panel

 

8. Click on the”Add” button under the Add a role assignment to add a new role.

9.  Fill the pop-up window with Role, I choose the Contributor role, which has the privilege to create and manage resources in the Resource Group. Based on your requirement you can select a role for your Service Principal.

 

Click the Save button to complete the action.

We have created a Service Principal. Next, it requires an authentication method to communicate with services. There are two types of authentication available. One is password-based and the other certificate-based.

Password-based authentication

To create a password-based authentication, go back to the Active Directory and select App Registration from the left side panel. Select the App which we created recently.

 

From the next window click on “Certificate & secrets”

Click the “New client secret button to create a new secret key.

Give a description and expiry for the secret key. Click the add button to generate the key. Keep the key in a safe place.

To confirm the service principal is working, we will try to login to the Azure cloud with the help of the generated secret key. For this, we required Application ID and Tenant ID which is associated with the App. These details can be found in the App overview dashboard.

Open the PowerShell and execute the below command sign in.

PS /home/techies> $AzCred = Get-Credential -UserName 1234d-sdd-898-4444-dsdsdw2
PowerShell credential request
Enter your credentials.
Password for user 12wede-34ew-333-cd80-8fda999: ********************************

PS /home/techies> Connect-AzAccount -ServicePrincipal -Credential $AzCred -Tenant 234w-df89b-1111-dee-2233sc

Here the username is the Application ID and password is the generated secret key. We stored these values in a variable called “$AzCred”.  The command will list the Resource Group associated with the Service principal subscription.

 

Certificate-based authentication

So far we have created a Service Principal and created a password authentication for it. Next, we will create a certificate-based authentication.  I have installed PowerShell Core on my ubuntu 18.04 server, so for generating I can use open SSL command. To generate an SSL certificate first we need to create a CSR ( Certificate Signing Request). For this execute below command.

openssl req -newkey rsa:4096 -nodes -keyout "sp-private.key" -out "sp-certificate-rqst.csr"

You will get a CSR file and key file after filling the requested certificate details like country, state, etc.  Please make sure to set a password for the private key. Next, generate a self-signed certificate with this key and CSR. For this execute below command.

openssl x509 -signkey "sp-private.key" -in "sp-certificate-rqst.csr" -req -days 365 -out "sp-cert.crt"

Now you have a certificate, private key and CSR file in your user home directory. To use it with Service Principal convert the certificate to “pfx” format. To convert, execute the below command.

openssl pkcs12 -export -out "sp.pfx" -inkey "sp-private.key" -in "sp-cert.crt"

At the time of pfx certificate generation, it will ask for a password, please remember it store in a safe place as it required to import the certificate in PowerShell.

 

To associate the certificate with the Service principal, upload it to the Azure portal. Login to Azure portal -> Active directory -> App registration. Click on the App name and select “Certificate & Secret”. Click the upload button to upload the certificate. Once you uploaded you will get a thumbprint, keep it safe as we need it for authentication.

In-order to work the certificate-based authentication Azure PowerShell can retrieve information from a local certificate store based on a certificate thumbprint. For this, we have to import the certificate (pfx format) to the PowerShell. ( This is applicable for PowerShell 6.x and later)

Execute below commands in PowerShell ( Click here to install PowerShell on Ubuntu)

techies@devops-azure:~$ pwsh
PowerShell 7.0.0
Copyright (c) Microsoft Corporation. All rights reserved.
https://aka.ms/powershell
Type 'help' to get help.

PS /home/techies>
$storeName = [System.Security.Cryptography.X509Certificates.StoreName]::My

$storeLocation =[System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser

$store = [System.Security.Cryptography.X509Certificates.X509Store]::new($storeName, $storeLocation)
$certPath = "/home/techies/pfx-cert.pfx"
$credentials = Get-Credential -Message "passpfx123"
PowerShell credential request
passpfx123
User: techies
Password for user techies: **********
$flag =[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable
$certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($certPath, $credentials.Password, $flag)
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$store.Add($Certificate)
$store.Close()

The password used to generate pfx certificate should be used for PowerShell credential request  for the user techies ( here it is passpfx123) or there will be a chance to get below error messages

If the password is wrong you will get below error.

MethodInvocationException: Exception calling ".ctor" with "3" argument(s): "error:23076071:PKCS12 routines:PKCS12_parse:mac verify failure"

We have completed storing a password in the PowerShell store. Next, try to connect to the Azure cloud with the certificate from the PowerShell, for this execute below command.

Connect-AzAccount -ApplicationId 06a754bf-9798-4898-b870-8fda524dc0eb -Tenant 42ff16a7-f89b-4479-beff-988fe69e74f2 -CertificateThumbprint 8C4BDDEA136E021294CB0483CA91744F736D7503

Account         SubscriptionName TenantId                Environment

-------         -------------- --------                 -----------
2222-1111-4898 Free Trial     42ff16a7-988fe69e74f2 AzureCloud

We have created a service principal and authenticated it with a password and certificate.

Leave a Reply

Your email address will not be published.