title: How to get connection string out of Azure KeyVault?
body: <p>A hypothetical web-site currently connects using:</p>
  
  <pre><code>public SqlConnection CreateConnection()
  {
     DbConnection connection = new SqlConnection();
     connection.ConnectionString = GetConnectionString();
     connection.Open();
  
     return connection;
  }
  </code></pre>
  
  <p>Where the magical connection string is stored in <code>web.config</code>:</p>
  
  <pre><code>String GetConnectionString()
  {
     //Get the connection string info from web.config
     ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings["db"];
  
     if (cs == null)
        throw new Exception("Could not locate DB connection string");
  
     return cs.ConnectionString;
  }
  </code></pre>
  
  <p>Now i'd like to move the connection string out of the web.config file into Azure KeyVault. How do you retrieve anything out of the Azure key vault?</p>
  
  <pre><code>String GetConnectionString()
  {
     //Get the connection string info from Azure KeyVault
     String connectionString = GetAzureSecret("dbConnectionString");
  
     if (String.IsNullOrWhitespace(connectionString)
        throw new Exception.Create("Could not connection string of Azure Key Vault");
  
     return connectionString;
  }
  </code></pre>
  
  <p>Except i just made up the easy-to-use Azure API. What is the <em>actual</em> api?</p>
  
  <h2>Untested attempt</h2>
  
  <pre><code>string GetAzureSecret(string key)
  {
      KeyVaultClient vault = new KeyVaultClient();
      vault.OnAuthenticate += VaultClientAuthenticate;
  
      var sec = await vault.GetSecretAsync(Key);
      return sec.Value;
  }
  
  public static async Task&lt;string&gt; VaultClientAuthenticate(string authority, string resource, string scope)
  {
     String clientID = "8675209";
     String clientSecret = "correct battery horse pencil";
  
     var authContext = new AuthenticationContext(authority);
     ClientCredential clientCred = new ClientCredential(clientID, clientSecret);
     AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);
  
     if (result == null)
        throw new Exception("Could not acquire token");
  
     return result.AccessToken;
  }
  </code></pre>
  
  <h2>Bonus Reading</h2>
  
  <ul>
  <li><a href="https://social.msdn.microsoft.com/Forums/azure/en-US/56bed4bd-6320-4f1f-9af5-556ae91bdf0f/storing-sql-connection-string-passwords-in-key-vault-for-my-cloud-services?forum=AzureKeyVault" rel="noreferrer">MSDN Forums: Storing sql connection string passwords in Key Vault for my Cloud Services</a></li>
  <li><a href="https://stackoverflow.com/questions/40706406/how-to-properly-store-connection-strings-in-azure">How to properly store connection strings in Azure?</a></li>
  <li><a href="https://stackoverflow.com/questions/2997903/easily-switching-connectionstrings-on-publish-to-azure?rq=1">Easily switching ConnectionStrings on publish to Azure</a></li>
  </ul>