How to connect to Azure Database using Managed Identity from Workflow framework?

Anish Reghunandanan 0 Reputation points
2023-01-11T09:13:59.21+00:00

Hi,

I am trying to connect to Azure Managed Database Instance using Managed Identity connection string. My Connection string is in the following format:

Data Source=

Azure SQL Database
Azure Static Web Apps
Azure Static Web Apps
An Azure service that provides streamlined full-stack web app development.
770 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Ryan Hill 25,981 Reputation points Microsoft Employee
    2023-01-12T15:13:55.4466667+00:00

    Hi [@Anish Reghunandanan]

    Even though you've tagged Static Web Apps, Tutorial: Connect to Azure databases from App Service without secrets using a managed identity is still applicable; so you can leverage those instructions.

    You can assign a System Managed identity to your static web app and then add that add that identity as a user to your Azure SQL database per the following command:

    CREATE USER [<app-name>] FROM EXTERNAL PROVIDER;
    ALTER ROLE db_datareader ADD MEMBER [<app-name>];
    ALTER ROLE db_datawriter ADD MEMBER [<app-name>];
    ALTER ROLE db_ddladmin ADD MEMBER [<app-name>];
    GO
    

    Once you've added the identity to your SQL instance, you add the connection string Server=tcp:<server-name>.database.windows.net;Database=<database-name>;TrustServerCertificate=True as an application setting and retrieve inside your application code. You also need to add Azure.Identity package to your application so that you can use DefaultAzureCredential. This code will leverage the identity of the application to retrieve token which is used to access the database.

    You can utilize the access token returned by DefaultAzureCredential on the SqlConnection object as follows:

    var conn = (System.Data.SqlClient.SqlConnection)Database.Connection;
    var credential = new Azure.Identity.DefaultAzureCredential();
    var token = credential.GetToken(new Azure.Core.TokenRequestContext(new[] { "https://database.windows.net/.default" }));
    conn.AccessToken = token.Token;