Using AddDistributedSqlServerCache with Managed Service Identity

274 Views Asked by At

Hi I have a question about using the SQL backed distributed cache as described in here https://learn.microsoft.com/en-us/entra/msal/dotnet/how-to/token-cache-serialization?tabs=aspnet

The code I'm using look like this:

 // SQL Server token cache
 app.AddDistributedTokenCache(services =>
 {
  services.AddDistributedSqlServerCache(options =>
  {
   // Requires to reference Microsoft.Extensions.Caching.SqlServer
   options.ConnectionString = @"...connection string goes here...";
   options.SchemaName = "dbo";
   options.TableName = "TestCache";
   options.DefaultSlidingExpiration = TimeSpan.FromMinutes(90);
  });
 });

When I do the local testing using the following connection string, it works fine: "Data Source=localhost\SQLEXPRESS;Initial Catalog=DefaultDb;Integrated Security=true;MultipleActiveResultSets=False;Encrypt=False;TrustServerCertificate=True"

But when I switch to the connection string for Azure SQL: "Data Source=some.database.windows.net;Initial Catalog=DefaultDb;Persist Security Info=False;MultipleActiveResultSets=False;Encrypt=False;TrustServerCertificate=True"

I get the following exception: Message "Login failed for user ''." string Source "Framework Microsoft SqlClient Data Provider"

My hunch is I might have to set the AccessToken like other part of our code does because we use Manage service identity when calling Azure SQL:

   SqlConnection connection = new SqlConnection(connectionStr);
   connection.AccessToken = accessToken;

The problem is SqlServerCacheOptions does not have a property that allows you to set the AccessToken. My question is how can I use the distributed SQL backed cache on an ASP.NET app that uses Azure SQL with Managed service identity.

0

There are 0 best solutions below