如果我在local.settings.json中设置AzureWebJobsServiceBus的连接字符串,则没有错误。但是,我想使用Azure Key-vault防止泄露连接字符串。
以下是我的错误:
Microsoft.Azure.WebJobs.Host:错误索引方法“ MyAzureFunc.Run”。 Microsoft.ServiceBus:服务总线连接字符串不是预期的格式。字符串中包含意外的属性,或者格式不正确。请先检查字符串。再试一次。
这是我的代码:
public static class MyAzureFunc
{
private static readonly SettingsContext _settings;
static MyAzureFunc()
{
_settings = new SettingsContext(new Settings
{
BaseUrl = Environment.GetEnvironmentVariable("BaseUrl"),
ServiceBusConnectionString = Environment.GetEnvironmentVariable("ServiceBus"),
certThumbprint = Environment.GetEnvironmentVariable("CertThumbprint"),
keyVaultClientId = Environment.GetEnvironmentVariable("KeyVaultClientId"),
ServiceBusSecretUrl = Environment.GetEnvironmentVariable("ServiceBusSecretUrl")
});
Environment.SetEnvironmentVariable("AzureWebJobsServiceBus", _settings.ServiceBusConnectionString);
}
[FunctionName("Func")]
public static async Task Run([ServiceBusTrigger(ServiceBusContext.MyQueueName)] BrokeredMessage msg, TraceWriter log)
{
......
}
}
public SettingsContext(Settings settings)
{
new MapperConfiguration(cfg => cfg.CreateMap<Settings, SettingsContext>()).CreateMapper().Map(settings, this);
if (!string.IsNullOrEmpty(settings.certThumbprint) && !string.IsNullOrEmpty(settings.keyVaultClientId))
{
var cert = Helpers.GetCertificate(settings.certThumbprint);
var assertionCert = new ClientAssertionCertificate(settings.keyVaultClientId, cert);
KeyVaultClient = GetKeyVaultClient(assertionCert);
if (ServiceBusConnectionString == "nil" && !string.IsNullOrEmpty(settings.ServiceBusSecretUrl))
{
ServiceBusConnectionString = KeyVaultClient.GetSecretAsync(settings.ServiceBusSecretUrl).Result.Value;
}
}
}
private static KeyVaultClient GetKeyVaultClient(ClientAssertionCertificate assertionCert)
{
return new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(async (string authority, string resource, string scope) =>
{
var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
var result = await context.AcquireTokenAsync(resource, assertionCert);
return result.AccessToken;
}));
}
答案 0 :(得分:1)
这实际上比您尝试的要简单得多;)请参见here。 KeyVault与Azure Functions / App Services本机集成,用于安全存储设置。
在您的local.settings.json文件中,您可以按原样使用连接字符串(以纯文本格式)。此文件永远不会签入。
在Azure中,您有一个具有相同名称的应用程序设置,但是您没有像使用纯文本连接字符串那样放置引用,而是对KeyVault设置进行了这样的引用:
@Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/ec96f02080254f109c51a1f14cdb1931)
您唯一需要做的就是启用功能的托管身份,并在KeyVault中授予该身份读取权限。