简体   繁体   English

通过 KeyVault 从 Azure 函数连接到 SQL Server

[英]Connect to SQL Server from Azure function by KeyVault

I try to connect to sql server from a local azure function by using key vault secrets.我尝试使用密钥库机密从本地 azure 函数连接到 sql server。 I set up a functions startup class to configure the connection:我设置了一个函数启动类来配置连接:

[assembly: FunctionsStartup(typeof(MyNamespace.Startup))]
//namespace
public class Startup : FunctionsStartup
{
    public Startup()
    {
    }

    public override void Configure(IFunctionsHostBuilder builder)
    {
        string basePath = IsDevelopmentEnvironment() ?
            Environment.GetEnvironmentVariable("AzureWebJobsScriptRoot") :
            $"{Environment.GetEnvironmentVariable("HOME")}\\site\\wwwroot";

        var configurationBuilder = new ConfigurationBuilder()
            .SetBasePath(basePath)
            .AddJsonFile("local.settings.json", optional: true, reloadOnChange: false)  // secrets go here. This file is excluded from source control.
            .AddEnvironmentVariables();

        var builtConfig = configurationBuilder.Build();

        var azureServiceTokenProvider = new AzureServiceTokenProvider();
        var keyVaultClient = new KeyVaultClient(
            new KeyVaultClient.AuthenticationCallback(
                azureServiceTokenProvider.KeyVaultTokenCallback));

        configurationBuilder.AddAzureKeyVault($"https://{builtConfig.GetSection("KeyVaultSettings")["KeyVaultName"]}.vault.azure.net/",
            keyVaultClient,
            new DefaultKeyVaultSecretManager());

        var builtConfigWithKeyVault = configurationBuilder.Build(); //necessary?

        // Registering services
        builder
            .Services
                .AddScoped<IUnitOfWork, UnitOfWork>()
                .AddDbContext<DomainDbContext>(
                    options => options.UseSqlServer(builtConfigWithKeyVault.GetSection("KeyVaultSettings")["DatabaseConnectionStringSecretName"]));
    }

    public bool IsDevelopmentEnvironment()
    {
        return "Development".Equals(Environment.GetEnvironmentVariable("AZURE_FUNCTIONS_ENVIRONMENT"), StringComparison.OrdinalIgnoreCase);
    }
}

In local.settings.json , I defined the key vault settings:local.settings.json ,我定义了密钥保管库设置:

"KeyVaultSettings": {
    "KeyVaultName": "KeyVault",
    "DatabaseConnectionStringSecretName": "ConnectionString"
}

My problem is that the connection is not set up, because in DBContextOptions, the connection string is "ConnectionString"我的问题是没有建立连接,因为在DBContextOptions中,连接字符串是“ConnectionString”

public DomainDbContext(IServiceProvider serviceProvider, DbContextOptions<DomainDbContext> options) : base(options)
{
    //options has wrong connection string
}

Is something wrong with the code or is it generally not possible to access key vault from local Azure function?!代码有问题还是通常无法从本地 Azure 函数访问密钥库?!

If you want to get a connection string from Azure key vault, please refer to the following code如果想从 Azure Key Vault 获取连接字符串,请参考以下代码

[assembly: FunctionsStartup(typeof(FunctionApp1.Startup))]
namespace FunctionApp1
{
    class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            string basePath = IsDevelopmentEnvironment() ?
            Environment.GetEnvironmentVariable("AzureWebJobsScriptRoot") :
            $"{Environment.GetEnvironmentVariable("HOME")}\\site\\wwwroot";

            var configurationBuilder = new ConfigurationBuilder()
                .SetBasePath(basePath)
                .AddJsonFile("local.settings.json", optional: true, reloadOnChange: false)
                .AddEnvironmentVariables();
            var currentConfiguration = configurationBuilder.Build();
            var azureServiceTokenProvider = new AzureServiceTokenProvider();
            var kvClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
            configurationBuilder
                        .AddAzureKeyVault($"https://{currentConfiguration["KeyVaultSettings:KeyVaultName"]}.vault.azure.net/",
                          kvClient, new DefaultKeyVaultSecretManager());
            var keyConfig = configurationBuilder.Build();
           
            var conStr= keyConfig.GetValue<string>(currentConfiguration["KeyVaultSettings:DatabaseConnectionStringSecretName"]);

            builder.Services
                    .AddDbContext<DomainDbContext>(options => options.UseSqlServer(conStr));
           


        }


        public bool IsDevelopmentEnvironment()
        {
            return "Development".Equals(Environment.GetEnvironmentVariable("AZURE_FUNCTIONS_ENVIRONMENT"), StringComparison.OrdinalIgnoreCase);
        }
    }
}

在此处输入图片说明

Besides, after you deploy the Function to Azure, we can use Azure key vault reference to simplify your code.此外,将 Function 部署到 Azure 后,我们可以使用 Azure Key Vault 引用来简化您的代码。 For more details, please refer to here and here欲了解更多详情,请参阅此处此处

For example例如

  1. Enable Azure MSI in Azure function在 Azure 功能中启用 Azure MSI

  2. Create an access policy in Key Vault for the application identity you created earlier在 Key Vault 中为之前创建的应用程序标识创建访问策略

  3. Add the reference in Azure Function Application Settings在 Azure 函数应用程序设置中添加引用

@Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/ec96f02080254f109c51a1f14cdb1931)
  1. Read the Application Settings in your code阅读代码中的应用程序设置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM