title: How do I authenticate a .NET Core Generic Host daemon app to AzureAD with MSAL or ADAL?
body: <p>I have created an app registration for the app in AzureAD. The app runs on prem and needs access to a Key Vault and my App Service REST API. All the accesses work fine when run under my Visual Studio credentials. But when deployed it will fail w/out the app authenticating. But, what libraries and code are required to authenticate the app?</p>
  
  <p>I have looked at the following:</p>
  
  <ul>
  <li><a href="https://github.com/Azure-Samples/active-directory-dotnetcore-daemon-v2" rel="nofollow noreferrer">https://github.com/Azure-Samples/active-directory-dotnetcore-daemon-v2</a> (does not use generic host)</li>
  <li><a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-daemon-app-configuration" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-daemon-app-configuration</a> (doesn’t work with generic host)</li>
  </ul>
  
  <p>Current Code:</p>
  
  <pre><code>public static async Task Main(string[] args)
  {    
      // Logging
      try
      {
          var host = CreateHostBuilder(args).Build();
          await host.RunAsync();
      }
      catch (Exception exception)
      {
          // Handle
      }
  }
  
  private static IHostBuilder CreateHostBuilder(string[] args)
  {
      return new HostBuilder()
                 .ConfigureHostConfiguration(config =&gt; { config.AddEnvironmentVariables("ASPNETCORE_"); })
                 .ConfigureAppConfiguration((context, config) =&gt; { AddConfigurationProviders(config); })
                 .ConfigureServices(AddServices)
                 .UseSerilog();
  }
  
  private static void AddConfigurationProviders(IConfigurationBuilder config)
  {
      config.AddJsonFile("appSettings.json", false);
  
      var configuration = config.Build();
  
      var azureServiceTokenProvider = new AzureServiceTokenProvider();
      var keyVaultClient = new KeyVaultClient(
              new KeyVaultClient.AuthenticationCallback(
              azureServiceTokenProvider.KeyVaultTokenCallback));
  
      config.AddAzureKeyVault(
              $"https://{configuration["keyVault"]}.vault.azure.net/",
              keyVaultClient,
      new DefaultKeyVaultSecretManager());            
  }
  </code></pre>