CodexBloom - Programming Q&A Platform

Azure Functions - Difficulty Accessing Azure SQL Database with Managed Identity in .NET 5

πŸ‘€ Views: 75 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-16
azure azure-functions sql-database managed-identity csharp

I'm upgrading from an older version and I'm working on a project and hit a roadblock. I'm trying to access an Azure SQL Database from an Azure Function using a managed identity, but I'm running into issues. When I attempt to run my function, I get the following behavior message: `Microsoft.Data.SqlClient.SqlException: Login failed for user 'Managed Identity'. Reason: Failed to open the database 'myDatabase' requested by the login. The login failed.` I have already enabled the managed identity for my Azure Function and granted it the necessary `db_datareader` and `db_datawriter` roles in the SQL Database. Here’s a snippet of my function code: ```csharp using System; using System.Data.SqlClient; using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; public static class SqlFunction { [FunctionName("SqlFunction")] public static async Task Run([TimerTrigger("0 */5 * * * *")] TimerInfo myTimer, ILogger log) { string connectionString = "Server=tcp:myserver.database.windows.net;Database=myDatabase;"; using (SqlConnection conn = new SqlConnection(connectionString)) { conn.AccessToken = await GetAccessTokenAsync(); await conn.OpenAsync(); log.LogInformation("Connection successful!"); } } private static async Task<string> GetAccessTokenAsync() { var azureServiceTokenProvider = new AzureServiceTokenProvider(); return await azureServiceTokenProvider.GetAccessTokenAsync("https://database.windows.net/"); } } ``` I’ve double-checked that the connection string is correct and uses the proper server name. I’m also running this in an Azure Function app that's set to run on .NET 5, and I added the `Microsoft.Azure.Services.AppAuthentication` NuGet package to handle the token acquisition. I've tested the token generation separately, and it seems to be working because it retrieves a token without behavior. However, for some reason, when I try to use that token to open the connection to the Azure SQL database, it fails. What am I missing here? Are there additional permissions or configurations that I need to consider when setting up the managed identity for Azure SQL access? I'm working on a web app that needs to handle this. Am I missing something obvious? I've been using Csharp for about a year now.