I have tried with the System Assigned Managed Identity:
- Created Azure Function App > Switched the System Assigned Managed Identity.
- Created SQL Server > Selected Set Admin as my account > Then Created the Database > Created the table and added the sample data:
SE [Pravusqltestdb]
GO
CREATE TABLE items (id INT NOT NULL, name VARCHAR(50) NOT NULL, number INT);
INSERT into items VALUES(1, 'Electronics', 10),(2, 'Homeneeds', 20);
Select * from items;
Next the below Query executed:
CREATE USER [PravisNet6FunApp] FROM EXTERNAL PROVIDER;
GO
ALTER ROLE db_datareader ADD MEMBER [PravisNet6FunApp];
ALTER ROLE db_datawriter ADD MEMBER [PravisNet6FunApp];
GO
Here PravisNet6FunApp
is the Function App Name.
Next, Modified the Function Code for fetching the access token using SQL Connection:
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.Azure.Services.AppAuthentication;
using System.Data.SqlClient;
namespace PravuSystemIdentity
{
public static class Function1
{
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
var tokenProvider = new AzureServiceTokenProvider();
string accessToken = await tokenProvider.GetAccessTokenAsync("https://pravusqldbserver.database.windows.net/.default");
log.LogInformation($"accessToken = {accessToken}");
var sqlconnection = Environment.GetEnvironmentVariable("sqlconnection");
using (SqlConnection conn = new SqlConnection(sqlconnection))
{
conn.AccessToken = accessToken;
conn.Open();
var statement = $"Select top 2 name from items";
log.LogInformation($"{statement}");
using (SqlCommand cmd = new SqlCommand(statement, conn))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
log.LogInformation($"{reader.GetString(0)}");
}
}
}
}
return new OkResult();
}
}
}
In the local.settings.json
, SQL Connection is defined., Published to Azure Portal Function App and defined the connection string under Function App > Configuration:
