public SqlConnection CreateConnection()
{
DbConnection connection = new SqlConnection();
connection.ConnectionString = GetConnectionString();
connection.Open();
return connection;
}
在 web.config
中存储神奇的连接字符串:
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;
}
我想把连接字符串从web.config文件中移出,放到Azure KeyVault中。你如何从Azure Key Vault检索任何内容?
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;
}
除了我刚刚编写的易于使用的Azure API之外,还有什么是 实际的 API?
未经测试的尝试
string GetAzureSecret(string key)
{
KeyVaultClient vault = new KeyVaultClient();
vault.OnAuthenticate += VaultClientAuthenticate;
var sec = await vault.GetSecretAsync(Key);
return sec.Value;
}
public static async Task<string> 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;
}