Search code examples
c#azureentity-frameworkazure-sql-databaseasp.net-identity

How to connect Entity Framework with Azure user assigned identity? Instead of using connection string


Microsoft has given documentation on how to connect through managed identity. it's okay for Azure AD user but I want to use User assigned identity which I've created in Azure portal.

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;

Code provided by Microsoft for creating connection with default Azure credential.

It was working with system assigned identity. Getting error while making connection for user assigned identity.


Solution

  • When connecting to an SQL server you basically have 2 options:

    1. Connect based on the identity of the calling process
    2. Connect based on the information in a connection string

    It looks like what you want to do is:

    1. Connect using a user assigned identity
    2. Do not place user name and password in the connection string

    To do this you must:

    1. Grant the user assigned identity access to SQL Server
    2. Change the identity of the process running your code to the user assigned identity