Azure Platform and Microsoft Technologies

AAD – Using Managed Service Identity (MSI) with Azure App Service and Azure SQL Database

Managed Identity Service is a useful feature to implement for the cloud applications you plan to develop in Azure. You can use this identity to authenticate to any service that supports Azure AD authentication without having any credentials in your code. The credentials never appear in the code or in the source control. It works by defining a service principal ID attributed to either a system-assigned (Azure Service instance) or a user-assigned (Azure stand-alone resource).

The difference between both is that for the system-assigned identity, the service principal ID is available only within the same subscription and the lifetime identity of the Azure Service instance is directly tied where its enabled on. If the instance is removed, the identity is also removed.

The service principal ID of a user-assigned identity is the same, only available within a same subscription but is managed separably from the life cycle of Azure instances to which its assigned.

In this article, i enabled the Managed Identity service for the web app with an Azure SQL database.

To give access to the web app to we will simply add the principal ID inside the SQL group. This will let the service principal ID of the web app to request a token to authenticate to the SQL database.

Add the service PrincipalID access to the SQL group

Azure SQL Database does not support creating logins or users from service principals created from Managed Service Identity so the way to do it is by adding the ID in the SQL groups that was previously given the rights to the database.

Modify your code to acquire a token

Add the library and the constructor :

using Microsoft.Azure.Services.AppAuthentication;
using System.Data.SqlClient;
using System.Web.Configuration;

This constructor configures a custom SqlConnection object to use an access token for Azure SQL Database from App Service. With the access token, your App Service app authenticates with Azure SQL Database with its managed identity.