I have a .NET 5 Azure Function running with a FUNCTIONS_WORKER_RUNTIME
config value of dotnet-isolated
.
The function app needs to connect to an Azure SQL database using EF Core 5.0.6.
I followed guidance from this post for EF configuration.
My custom dbcontext
is now:
public class SmsOrderContext : DbContext
{
private readonly AzureServiceTokenProvider azureServiceTokenProvider;
public SmsOrderContext(DbContextOptions<SmsOrderContext> options, AzureServiceTokenProvider azureServiceTokenProvider) : base(options)
{
RelationalDatabaseCreator databaseCreator =
(RelationalDatabaseCreator)this.Database.GetService<IDatabaseCreator>();
databaseCreator.EnsureCreated();
this.azureServiceTokenProvider = azureServiceTokenProvider;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
SqlConnection connection = new SqlConnection();
string? envConString = Environment.GetEnvironmentVariable(ConfigConstants.SqlSvrConnString);
connection.ConnectionString = envConString ?? "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=SmsRouter";
if (azureServiceTokenProvider != null)
connection.AccessToken = azureServiceTokenProvider.GetAccessTokenAsync("https://database.windows.net/").Result;
optionsBuilder.UseSqlServer(connection);
}
}
The condition for checking SqlSvrConnString
environment variable is there so that I can run the app locally - where it uses localdb (this works fine) rather than Azure
In program.main I have:
.ConfigureServices(s =>
{
s.AddSingleton<AzureServiceTokenProvider>(new AzureServiceTokenProvider());
s.AddDbContext<SmsOrderContext>();
}
On my function app, the "Status" toggle for Identity\System assigned set to "On"
When I trigger the Azure function (from a http request), I see the following exception in Application Insights:
Failure Exception: Microsoft.Data.SqlClient.SqlException (0x80131904):
Login failed for user ''
I think this suggests the identity is not being passed to Sql Server? Can anyone see where I went wrong please?