title: EF Core & Azure SQL with Managed Identity (no `IDBAuthTokenService`)
body: <p>I'm trying to connect to an Azure SQL Database deployed to Azure App Services. Essentially I'm trying to do what is described in [this question][1] from January 2019, but <code>IDBAuthTokenService</code> does not exist in <code>Microsoft.Azure.Services.AppAuthentication</code> (if it ever did, there are no references anywhere).</p>
  
  <ul>
  <li><p>What is the right way to do this now?</p></li>
  <li><p>Should I ditch <code>DbContext</code> and create a ConnectionFactory myself instead? (I've seen a colleague do this, but using <code>DbContext</code> seems like the idiomatic way to do it in EF Core).</p></li>
  </ul>
  
  <p><strong>Startup.cs</strong></p>
  
  <pre><code>public void ConfigureServices(IServiceCollection services)
  {
      //code ignored for simplicity
      services.AddDbContext&lt;MyCustomDBContext&gt;();
  
      services.AddTransient&lt;IDBAuthTokenService, AzureSqlAuthTokenService&gt;();
  }
  </code></pre>
  
  <p><strong>MyCustomDBContext.cs</strong></p>
  
  <pre><code>public partial class MyCustomDBContext : DbContext
  {
      public IConfiguration Configuration { get; }
      public IDBAuthTokenService authTokenService { get; set; }
  
      public MyCustomDbContext(IConfiguration configuration, IDBAuthTokenService tokenService, DbContextOptions&lt;MyCustomDBContext&gt; options)
          : base(options)
      {
          Configuration = configuration;
          authTokenService = tokenService;
      }
  
      protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
      {
          SqlConnection connection = new SqlConnection();
          connection.ConnectionString = Configuration.GetConnectionString("defaultConnection");
          connection.AccessToken = authTokenService.GetToken().Result;
  
          optionsBuilder.UseSqlServer(connection);
      }
  }
  </code></pre>
  
  <p><strong>AzureSqlAuthTokenService.cs</strong></p>
  
  <pre><code>public class AzureSqlAuthTokenService : IDBAuthTokenService
  {
      public async Task&lt;string&gt; GetToken()
      {
          AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
          var token = await provider.GetAccessTokenAsync("https://database.windows.net/");
  
          return token;
      }
  }
  </code></pre>
  
  <p>[<a href="https://stackoverflow.com/questions/54187241/ef-core-connection-to-azure-sql-with-managed-identity?rq=1][1]">EF Core Connection to Azure SQL with Managed Identity</a></p>