如何从Azure KeyVault中获取连接字符串? [英] How to get connection string out of Azure KeyVault?

查看:329
本文介绍了如何从Azure KeyVault中获取连接字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设的网站当前使用以下方式进行连接:

A hypothetical web-site currently connects using:

public SqlConnection CreateConnection()
{
   DbConnection connection = new SqlConnection();
   connection.ConnectionString = GetConnectionString();
   connection.Open();

   return connection;
}

神奇的连接字符串存储在web.config中的位置:

Where the magical connection string is stored in 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密钥库中检索任何内容?

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?

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.什么是 actual api?

Except i just made up the easy-to-use Azure API. What is the actual 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;
}

奖金阅读

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆