我有这种情况:我有一个 Azure 函数,它从不同的服务调用一些 REST api。此其他服务需要证书。
如果我在 Startup.cs 中的依赖项注入期间尝试添加证书,则找不到证书。似乎 Startup.Configure 在加载所有证书之前运行(?)。
因此,我需要能够在 azure 函数本身内将证书加载到 httpclient。但是,除了某些标头之外,IHttpClientFactory 似乎没有任何机制来更改由 CreateClient 创建的客户端。如何稍后在调用堆栈中添加证书(将通过 HttpClientHandler.ClientCertificates.Add() 完成)?
// Startup.cs::Configure
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddLogging();
// My cert is stored in keyvault, so I go get it from there for the thumbprint
string certThumbprint = CertificateUtils.GetCertificateThumbprintFromKeyVault();
// This call tries to find the certificate with that thumbprint in CertStore.My
X509Certificate2 cert = CertificateUtils.GetCertificate(certThumbprint);
if (cert == null)
{
throw new MyException("Unable to retrieve your certificate from key vault");
}
using HttpClientHandler myApiHandler = new HttpClientHandler();
MyApiHandler.ClientCertificates.Add(cert);
builder.Services.AddHttpClient<IMyAPI, MyAPI>("MyApi", client => { client.BaseAddress = new Uri("<baseurl>"); })
.ConfigurePrimaryHttpMessageHandler(() => myApiHandler);
}
// CertificateUtils:
public static X509Certificate2 GetCertificate(
string certId,
StoreLocation storeLocation = StoreLocation.LocalMachine,
StoreName storeName = StoreName.My,
X509FindType findType = X509FindType.FindByThumbprint)
{
X509Certificate2Collection set = GetCertificates(storeLocation, storeName, findType, certId, false);
if (set.Count != 1 || set[0] == null)
{
string exceptionDetails = set.Count != 1 ? "with certificate count of " + set.Count : "element at position 0 is null";
throw new ConfigException($"Failed to retrieve certificate {certId} from store {storeLocation}\\{storeName}, {exceptionDetails}");
}
return set[0];
}
private static X509Certificate2Collection GetCertificates(
StoreLocation storeLocation,
StoreName storeName,
X509FindType findType,
string certId,
bool validOnly)
{
X509Store certStore = new X509Store(storeName, storeLocation);
certStore.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
try
{
return certStore.Certificates.Find(findType, certId, validOnly);
}
finally
{
certStore.Close();
}
}
}
// MyAPI
public class MyAPI : MyAPI
{
private readonly HttpClient HttpClient;
private IHttpClientFactory HttpClientFactory;
public MyAPI(IHttpClientFactory httpClientFactory)
{
this.HttpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory));
this.HttpClient = httpClientFactory.CreateClient("MyApi");
}
public Data DoSomething(string name)
{
Uri uri = new Uri($"{this.HttpClient.BaseAddress}/Some/REST/API?name={name}");
HttpResponseMessage response = this.HttpClient.GetAsync(uri).Result;
response.EnsureSuccessStatusCode();
string body = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<Data>(body);
}
}
public class MyAzureFunc
{
private readonly IMyAPI MyAPI;
private readonly ILogger Log;
public MyAzureFunc(ILogger<MyAzureFunc> log, IMyAPI myApi)
{
this.Log = log;
this.MyAPI = myApi;
}
[FunctionName("MyAzureFunc")]
public async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]
HttpRequest req)
{
// ... standard boilerplate stuff to read the name=Rusty part from the GET call ...
// Call the 3rd party service that requires the cert to get some data
MyData data = this.MyAPI.DoSomething(name);
// ... then do something with the data
return new HttpResponseMessage(HttpStatusCode.OK);
}
}
在本地调试中启动我的天蓝色函数时,它立即在 GetCertificate 中失败。我成功地从我的密钥库中获取了证书指纹,但它在我的 CertStore.My 中找到的证书集不完整(它返回 4 个证书,其中没有一个在我的个人存储中?!?)。这就是让我相信 Startup.Configure 在 azure 函数加载证书之前发生的原因。
在尝试使用 Microsoft.Extensions.Http + DI + Polly 的推荐方法之前,我在 MyAPI.DoSomething 函数本身的函数中如下所示:
string certThumbprint = CertificateUtils.GetCertificateThumbprintFromKeyVault();
X509Certificate2 cert = CertificateUtils.GetCertificate(certThumbprint, storeLocation: StoreLocation.CurrentUser);
using HttpClientHandler handler = new HttpClientHandler();
handler.ClientCertificates.Add(cert);
using HttpClient client = new HttpClient(handler);
response = await client.GetAsync(uri);
response.EnsureSuccessStatusCode();
这工作得很好。
所以,我在想的是,由于在调用 Startup.cs 时证书显然不可用,所以我需要能够在初始化 HttpClient 的位置添加证书
this.HttpClient = httpClientFactory.CreateClient("MyApi");
// Get my certificate here and add it to the client via HttpClientHandler or such
或者,如果不是在 Startup.Configure 之后没有加载证书,为什么我的本地商店中的所有证书都没有被提取,我该如何让它正常工作?