Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Hosted-services / Azure

Articles: Login to Azure with PowerShell Non-interactively

0.00/5 (No votes)
9 Feb 2020CPOL2 min read 4.7K  
How to non-interactively login to Azure with PowerShell
The Login-AzureRmAccount PowerShell command allows you to login to your Azure account from PowerShell. However, it brings up a prompt and you have to manually type in your credentials. Obviously this is fine for development or things you are doing for one time administration. But in order to have fully automated scripts, this is one of the first pieces in the puzzle, especially when you are likely to be running these on a build server and you don't want an account that is tied to an actual person.

Creating a Service Principal

You certainly don’t want to have your personal signin credentials in the script. You need a service account that has just enough permissions to run the scripts that are being run.

This is accomplished with service principal which is an instance of an application on your Active Directory which you grant access to resources.

1. Login to your Azure account with:

PowerShell
Login-AzureRmAccount

2. Then we need to create an Active Directory application.

PowerShell
$displayName = "App Display Name"
$homePage = "http://YourApplicationHomePage"
$identifierUris = "http://YourApplicationUri"
$password = "APasswordHere"
$app = New-AzureRmADApplication –DisplayName $displayName 
       –HomePage $homePage –IdentifierUris $identifierUris  –Password $password

3. Create the Service Principal.

Now we need to create a service principal for that application which needs to access resources. This takes the applicationId of the application we created above.

PowerShell
New-AzureRmADServicePrincipal –ApplicationId $app.ApplicationId

4. Grant the Service Principal Roles.

You can view a list of the default roles at this link.

PowerShell
New-AzureRmRoleAssignment –RoleDefinitionName Contributor 
                          –ServicePrincipalName $app.ApplicationId

Authenticating Using a Service Principal

1. Create a PSCredential Object

PowerShell
$username = "YourUserName"
$pass = ConvertTo-SecureString "YourPassword" -AsPlainText –Force
$cred = New-Object -TypeName pscredential –ArgumentList $username, $pass

2. Get the TenantId from your Subscription

PowerShell
$tenant = (Get-AzureRmSubscription).TenantId

Login With the Credential Object

PowerShell
Login-AzureRmAccount -Credential $cred -ServicePrincipal –TenantId $tenant

Save Token to Login Later

You can save the profile as a token and login with that token later. This however does expire, and typically lasts around 12 hours.

PowerShell
Save-AzureRmProfile -Path c:\AzureLoginToken.json

Next time you want to login, just load the Profile.

PowerShell
Select-AzureRmProfile -Path c:\AzureLoginToken.json

Authenticating Using a Service Principal and Certificate

This will look mostly familiar to the above, except we first must generate the certificate that we are going to use and then create the AD Application with that certificate.

1. Login to Azure

PowerShell
Login-AzureRmAccount

2. Create certificate

PowerShell
$cert = New-SelfSignedCertificate -CertStoreLocation "cert:\CurrentUser\My" 
                                  -Subject "CN=exampleapp" -KeySpec KeyExchange
$keyValue = [System.Convert]::ToBase64String($cert.GetRawCertData())

3. Create AD Application

PowerShell
$azureAdApplication = New-AzureRmADApplication -DisplayName "exampleapp" 
                      -HomePage "https://www.contoso.org" 
                      -IdentifierUris "https://www.contoso.org/example" 
                      -KeyValue $keyValue -KeyType AsymmetricX509Cert 
                      -EndDate $cert.NotAfter -StartDate $cert.NotBefore      

4. Create Service Principal

PowerShell
New-AzureRmADServicePrincipal -ApplicationId $azureAdApplication.ApplicationId

5. Assign roles to Service Principal

PowerShell
New-AzureRmRoleAssignment -RoleDefinitionName Contributor 
                          -ServicePrincipalName $azureAdApplication.ApplicationId.Guid

Create Login Script for Certificate

1. Get Application Id

PowerShell
$applicationId = $azureAdApplication.ApplicationId
# Alternatively
# $applicationId = (Get-AzureRmADApplication 
                    -IdentifierUri "https://www.yourappURL.com").ApplicationId

2. Get thumbprint of the Certificate

PowerShell
$thumbprint = $cert.Thumbprint
# Alternatively
# $thumbprint = (Get-ChildItem -Path cert:\CurrentUser\My\* -DnsName exampleapp).Thumbprint

3. Get the Tenant

PowerShell
$tenantId = (Get-AzureRmSubscription).TenantId

4. Save File called login.ps1

This script is the login script that you will use, it contains the thumbprint, applicationId and tenantId needed to login as the newly created Service Principal.

PowerShell
$loginCommand = "Add-AzureRmAccount -ServicePrincipal -CertificateThumbprint $thumbprint 
                 -ApplicationId $applicationId -TenantId $tenantId"
Add-Content <span class="s1">'c:\login.ps1' $loginCommand

Wrap Up

Hopefully, that has given you a few options and taken you through how to login non-interactively into Azure.

Script examples are on GitHub here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)