How to connect to an Azure Key Vault and Azure SQL Database using the same Token Credential

If you’ve ever built a native application that reads its secrets from Azure Key Vault and also connects to an Azure SQL Database, you’ve probably wondered how to let your users sign in once and have that same identity work for both.

In theory, this should be simple. You create a single InteractiveBrowserCredential, hand it to your SecretClient, and then use it again for the database connection. However, in practice, you’ll find that the database connection doesn’t pick up the token that was just acquired for the key vault, and you end up being prompted to sign in a second time.

If you are looking for a way to overcome this, read on!

In this article, I explain why this happens and show you how to share a single token credential between your Azure Key Vault and Azure SQL Database in a .NET application using Entity Framework Core.

The problem

The reason for this behaviour is Continuous Access Evaluation (CAE). Azure Key Vault uses CAE, so the Azure SDK requests a CAE-enabled token for it. Azure SQL Database, on the other hand, does not request CAE tokens by default.

As far as the code is concerned, these are two different kinds of tokens. The cached token that was acquired for the key vault can’t be reused when the database connection asks for a non-CAE token, and so authentication for the database doesn’t work as you would expect.

Thankfully, all is not lost. The fix is to make sure that both resources request CAE-enabled tokens, so that they share the same cached credentials.

The solution

There are two parts to this. First, we authenticate up front with CAE enabled. Second, we make Entity Framework Core request its Azure SQL access token using CAE as well.

For this demo, I’m building a simple console application with an AppDbContext that exposes a single ‘Todos’ table. The application connects to an Azure Key Vault that contains a secret named ‘MySecret’ and connects to an Azure SQL Database that hosts the Todos database.

Authenticating up front

The first step is to create the credential and authenticate, specifying that CAE is enabled in the TokenRequestContext.

var credential = new InteractiveBrowserCredential();

await credential.AuthenticateAsync(new TokenRequestContext(
    ["https://vault.azure.net/.default"],
    isCaeEnabled: true));

The above code opens the browser, requesting the user to sign in. The returned authentication record is cached, so subsequent token requests can be satisfied silently.

The credential can now be passed to the SecretClient, which will be used to add the Azure Key Vault as a configuration source.

var configurationSecretClient = new SecretClient(
    new Uri(configurationKeyVaultUri),
    credential);
 
configurationBuilder.AddAzureKeyVault(configurationSecretClient, new KeyVaultSecretManager());
 
var configuration = configurationBuilder.Build();

Creating the Azure SQL authentication interceptor

Next, we need a way to attach an access token that is obtained from the same credential to our Azure SQL connection. A clean way to achieve this is with an EF Core interceptor that sets the access token on the SqlConnection just before it is opened.

using Azure.Core;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore.Diagnostics;
using System.Data.Common;
 
namespace AzureSqlDemo.Data;
 
public class AzureSqlAuthenticationInterceptor : DbConnectionInterceptor
{
    private static readonly string[] _scopes = ["https://database.windows.net/.default"];
 
    private readonly TokenCredential _credential;
 
    public AzureSqlAuthenticationInterceptor(TokenCredential credential)
    {
        _credential = credential;
    }
 
    public override InterceptionResult ConnectionOpening(
        DbConnection connection,
        ConnectionEventData eventData,
        InterceptionResult result)
    {
        if (connection is SqlConnection sqlConnection)
        {
            sqlConnection.AccessToken = _credential
                .GetToken(CreateRequestContext(), default)
                .Token;
        }
 
        return base.ConnectionOpening(connection, eventData, result);
    }
 
    public override async ValueTask<InterceptionResult> ConnectionOpeningAsync(
        DbConnection connection,
        ConnectionEventData eventData,
        InterceptionResult result,
        CancellationToken cancellationToken = default)
    {
        if (connection is SqlConnection sqlConnection)
        {
            var accessToken = await _credential.GetTokenAsync(CreateRequestContext(), cancellationToken);
 
            sqlConnection.AccessToken = accessToken.Token;
        }
 
        return await base.ConnectionOpeningAsync(connection, eventData, result, cancellationToken);
    }
 
    private static TokenRequestContext CreateRequestContext() => new(_scopes, isCaeEnabled: true);
}

In the above code, the interceptor accepts any TokenCredential and requests a token for the Azure SQL scope. The important part is the CreateRequestContext method, which sets isCaeEnabled to true. This ensures that the token request lines up with the CAE-enabled token that was cached when we authenticated for the key vault.

Both the synchronous and asynchronous overrides are implemented, as EF Core will call whichever method is appropriate for the operation being performed.

Creating a sample entity

Below is the shape of the sample Todo entity that we’ll use when querying the Azure SQL database.

namespace AzureSqlDemo.Entities;
 
public class Todo
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public required string Title { get; set; }
    public bool Completed { get; set; }
}

You’ll need to create the matching schema or enable EF Core Migrations so that you have a ‘Todos’ table to work with.

Creating the DbContext

Below is the source code for the AppDbContext that we’ll register in our startup logic to configure the entities that Entity Framework Core can access.

using AzureSqlDemo.Entities;
using Microsoft.EntityFrameworkCore;
 
namespace AzureSqlDemo.Data;
 
public class AppDbContext : DbContext
{
    public DbSet<Todo> Todos { get; set; }
 
    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }
 
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
 
        var todoEntity = modelBuilder.Entity<Todo>();
 
        todoEntity.Property(t => t.Title)
            .IsRequired()
            .HasMaxLength(256);
 
        modelBuilder.Entity<Todo>()
            .Property(t => t.Completed)
            .HasDefaultValue(false);
    }
}

Configuration

The appsettings.json for the Console App should be structured as follows.

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=jc-sample-sql.database.windows.net;Database=todos-db;"
  },
  "KeyVault": {
    "Uri": "https://jc-sample-kv.vault.azure.net/"
  }
}

Since we’re going to use our custom authentication interceptor, the connection string doesn’t contain any credentials or an Authentication setting; the interceptor takes care of that. This means that for most scenarios, we only need to specify the server and database name.

Note that the signed-in user will need to have access to the Azure Key Vault secrets, and also have a corresponding user created in the Azure SQL Database (e.g. using CREATE USER ... FROM EXTERNAL PROVIDER).

Registering the interceptor

The last step is to register the interceptor when configuring the DbContext, passing in the same credential instance that was used for the key vault.

var connectionString = configuration.GetConnectionString("DefaultConnection")
    ?? throw new InvalidOperationException("DefaultConnection string is not configured.");
 
var serviceCollection = new ServiceCollection();
 
serviceCollection.AddDbContext<AppDbContext>(options => options
    .UseSqlServer(connectionString)
    .AddInterceptors(new AzureSqlAuthenticationInterceptor(credential)));
 
using var serviceProvider = serviceCollection.BuildServiceProvider();

Trying it out

With everything wired up, we can try to retrieve a secret from the key vault and query the database using the same credential to make sure our code is working as expected.

KeyVaultSecret secret = await configurationSecretClient.GetSecretAsync("MySecret");
Console.WriteLine($"Secret value: {secret.Value}");
 
using var dbContext = serviceProvider.GetRequiredService<AppDbContext>();
 
var todoCount = await dbContext.Todos.CountAsync();
Console.WriteLine($"Current todo count: {todoCount}");

When you run the application, you should be prompted to sign in only once via the browser. After that, both the key vault request and the database query should succeed without any further prompts.

Below is the full source code listing for Program.cs for your reference.

using Azure;
using Azure.Core;
using Azure.Extensions.AspNetCore.Configuration.Secrets;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using AzureSqlDemo.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
 
Console.WriteLine("Loading configuration...");
 
var configurationBuilder = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", false);
 
var startupConfiguration = configurationBuilder.Build();
 
var configurationKeyVaultUri = startupConfiguration["KeyVault:Uri"]
    ?? throw new InvalidOperationException("KeyVault URI is not configured.");
 
var credential = new InteractiveBrowserCredential();
 
Console.Clear();
Console.WriteLine("Authenticating, please check browser...");
 
await credential.AuthenticateAsync(new TokenRequestContext(
    ["https://vault.azure.net/.default"],
    isCaeEnabled: true));
 
Console.Clear();
Console.WriteLine("Configuring KeyVault...");
 
var configurationSecretClient = new SecretClient(
    new Uri(configurationKeyVaultUri),
    credential);
 
configurationBuilder.AddAzureKeyVault(configurationSecretClient, new KeyVaultSecretManager());
 
var configuration = configurationBuilder.Build();
 
Console.Clear();
Console.WriteLine("Configuring database...");
 
var connectionString = configuration.GetConnectionString("DefaultConnection")
    ?? throw new InvalidOperationException("DefaultConnection string is not configured.");
 
var serviceCollection = new ServiceCollection();
 
serviceCollection.AddDbContext<AppDbContext>(options => options
    .UseSqlServer(connectionString)
    .AddInterceptors(new AzureSqlAuthenticationInterceptor(credential)));
 
using var serviceProvider = serviceCollection.BuildServiceProvider();
 
Console.Clear();
 
try
{
    Console.WriteLine("Getting secret from KeyVault...");
    KeyVaultSecret secret = await configurationSecretClient.GetSecretAsync("MySecret");
    Console.WriteLine($"Secret value: {secret.Value}");
}
catch (RequestFailedException ex)
{
    Console.WriteLine("Exception: {0}", ex.Message);
}
 
Console.WriteLine();
 
try
{
    Console.WriteLine("Querying database...");
    using var dbContext = serviceProvider.GetRequiredService<AppDbContext>();
 
    var todoCount = await dbContext.Todos.CountAsync();
    Console.WriteLine($"Current todo count: {todoCount}");
}
catch (Exception ex)
{
    Console.WriteLine("Exception: {0}", ex.Message);
}
 
Console.WriteLine("Press any key to exit...");
Console.ReadKey(intercept: true);

Note that the following NuGet packages are required for the Console App to compile.

Summary

In this article, I explained why a credential used to access Azure Key Vault can’t be reused for Azure SQL Database out of the box; Azure Key Vault uses CAE, but Azure SQL Database doesn’t by default, so the cached token doesn’t match.

I showed how to authenticate up front with CAE enabled and how to create an EF Core interceptor that requests an Azure SQL access token with CAE enabled as well.

Lastly, I demonstrated how to register the interceptor so that a single InteractiveBrowserCredential can be shared between both services.


💡 Thanks for reading! I love sharing what I learn and always respond to comments and questions.

If this post saved you time or solved a problem, consider supporting me with a coffee — it helps keep the blog running and the content flowing 🚀

Comments