我具有以下代码来在Azure中获取关键文件库机密:
var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetToken));
var sec = await kv.GetSecretAsync(ConfigurationManager.AppSettings["SomeURI"]);
secretValue = sec.Value ;
在App Config中,我有:
<add key="SomeURI" value="https://baseURL/KeyName/b75cabsdf45667nhjhe516c674457" />
由于我在应用程序中使用了很多次,因此我创建了一个类并称为该类。该类如下所示:
public static class KeyVaultFetch
{
public async static Task<string> GetCachedSecret(string secretname)
{
try
{
string BaseUri = ConfigurationManager.AppSettings["keyvaultBaseURI"].ToString();
var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetToken));
var secretbundle = await kv.GetSecretAsync($"{BaseUri}{secretname}").ConfigureAwait(false);
return secretbundle.Value;
}
catch (Exception ex)
{
log.Error("Exception raised in GetCachedSecret.");
log.Error("Exception Details: " + ex.Message);
log.Error("Inner Exception Details: " + ex.InnerException);
throw;
}
}
public static async Task<string> GetToken(string authority, string resource, string scope)
{
try
{
var authContext = new AuthenticationContext(authority);
ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);
if (result == null)
throw new InvalidOperationException("Failed to obtain the JWT token");
return result.AccessToken;
}
catch (Exception ex)
{
log.Error("Exception raised while Getting token : " + ex.Message);
log.Error("Inner Exception Details: " + ex.InnerException);
throw;
}
}
}
我已经在下面的行中写道,每次都可以获取秘密:
secretValue = await KeyVaultFetch.GetCachedSecret(keyName);
但是在运行代码时,我遇到了以下异常:
Exception raised in GetCachedSecret.
Exception Details: Invalid ObjectIdentifier: https://baseURL/. Bad number of segments: 2
我在做什么错。有人可以向我解释吗?
答案 0 :(得分:1)
您应该使用带有2个参数的GetSecretAsync:
await kv.GetSecretAsync(BaseUri, secretname);
至少我们的应用程序就是这样:)