Authenticating using a Service Principal

Azure service principal is a security identity created within Azure Active Directory & it is used by user-created apps, services, and automation tools to access specific Azure resources. You can assign permissions to the service principal that are different than your own Azure account permissions.

Creating a Service Principal

  1. Create an Application in Azure Active Directory which will create an associated Service Principal.
  2. Go to Application & you will need to take note of the \”Application ID (client_id)\” and the \”Directory (tenant) ID(tenant_id) . Then, click on Certificates & Secrets from left navigation bar.SP1
  3. Click on New client secret then fill the description & select expiry year.SP2
  4. Once the Client Secret has been generated it will be displayed on screen.This is only displayed once so be sure to copy it now (otherwise you will need to regenerate a new secret). This value is the client_secret you will need.SP3

Assign Role to Service Principal

  1. Once Service Principal will be created in the Azure AD, we can grant it permissions in Subscription or in Resource Group level.
  2. Go to Subscription you wish to use , then click Access Control (IAM), and then Add > Add role assignment. For more details related to IAM role refer this: Azure built-in roles. If you want to assign role in Resource Group level, then go to Resource Group > Access Control (IAM) > Add > Add role assignment.

 

Powershell script to Login via Service Principal

Fill the parameters & run the below command to login as a Service Principal:

$client_id =\"<>\"
$tenant_id= \"<<Directory ID"
$client_secret=\"<>\"
$secret = ConvertTo-SecureString $client_secret -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential($client_id, $secret)
Add-AzureRmAccount -Credential $Cred -TenantId $tenant_id -ServicePrincipal

Leave a comment