Sign into Azure with a service principal using the Azure CLI

Service principals are accounts not tied to any particular user, which you can assign permissions through predefined roles. Authenticating with a service principal is the best way to write secure scripts or programs. It lets you apply both permissions restrictions and locally stored static credential information. To learn more about service principals, see Work with Azure service principals using the Azure CLI.

To sign in with a service principal, you need:

  • The URL or name associated with the service principal.
  • The service principal client secret, or the X509 certificate used to create the service principal in PEM format.
  • The tenant associated with the service principal, as either an .onmicrosoft.com domain or Microsoft Entra tenant ID.

Note two important facts when working with service principals and the Azure CLI:

  • A CERTIFICATE must be appended to the PRIVATE KEY within a PEM file. For an example of a PEM file format, see Certificate-based authentication.

  • If your service principal uses a certificate that is stored in Key Vault, that certificate's private key must be available without signing in to Azure. To retrieve the certificate for az login, see Retrieve certificate from Key Vault.

To log in with a client secret, use the following command:

az login --service-principal --username APP_ID --password CLIENT_SECRET --tenant TENANT_ID

To log in with a certificate, use the following command:

az login --service-principal --username APP_ID --certificate /path/to/cert.pem --tenant TENANT_ID

Important

To avoid displaying your password on console when using az login interactively, use the read -s command under bash.

read -sp "Azure password: " AZ_PASS && echo && az login --service-principal --username <app-id> --password $AZ_PASS --tenant <tenant>

Under PowerShell, use the Get-Credential cmdlet.

$AzCred = Get-Credential -UserName <app-id>
az login --service-principal --username $AzCred.UserName --password $AzCred.GetNetworkCredential().Password --tenant <tenant>

See also