HowTo: Authenticate to Azure using a Service Principal

Official Content

Extract from Microsoft doc

"An Azure service principal is an identity created for use with applications, hosted services, and automated tools to access Azure resources. This access is restricted by the roles assigned to the service principal, giving you control over which resources can be accessed and at which level. For security reasons, it's always recommended to use service principals with automated tools rather than allowing them to log in with a user identity."

In sum, for a service (it can be any Azure service, in particular, Azure Functions) to connect to resources in an Azure subscription, it needs an associated service principal within that subscription's tenant. Each service is represented by an Azure Active Directory (AAD) application. This application has an associated service principal within each tenant to which it needs access.

To create a Service Principal (Password-based authentication) –using the Az CLI (as stated in the document mentioned above)– do the following:

az ad sp create-for-rbac --name ServicePrincipalName

Example

>az ad sp create-for-rbac --name GXFuncSP2
Changing "GXFuncSP2" to a valid URI of "http://GXFuncSP2", which is the required format used for service principal names
Creating a role assignment under the scope of "/subscriptions/.................."
  Retrying role assignment creation: 1/36
{
  "appId": "8d3debc6-4346-42c8-xxxxxxxxxxxxx",
  "displayName": "GXFuncSP2",
  "name": "http://GXFuncSP2",
  "password": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "tenant": "5ec7bbf9-1872-46c9-b201-a1e181996b35"
}

The default role for a service principal is Contributor. This role has full permissions to read and write to an Azure account. 

The Application defined can be seen in the Azure Portal, through the "Azure Active Directory" -> App registrations option:

image_2020129162053_1_png

By selecting the corresponding Application, you can get the Application ID and the Tenant ID (required to configure the "Service Principal Application ID" and "Service Principal Tenant ID" properties when deploying the application to Azure functions).

image_202012102171_1_png

See also

For a clear explanation of these concepts, read this blog.