如何在.net core 3.1中的依赖注入设置之外向IHttpClientFactory httpclient添加证书



我有这样的场景:我有一个Azure函数,它从不同的服务调用一些RESTapi。此其他服务需要证书。

如果我在Startup.cs中的依赖项注入过程中尝试添加证书,则找不到证书。似乎启动。在加载所有证书之前运行配置(?(。

因此,我需要能够在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);
}
}

在本地调试中启动我的azure函数时,它立即在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

或者,如果不是在启动后没有加载证书的情况。配置,为什么我的本地存储中的所有证书都没有被提取,我该如何使其正常工作?

这篇文章解决了我的问题。

如何使用ConfigurePrimaryHttpMessageHandler通用

至于本地证书,我用错误的StoreLocation调用了自己的GetCertificate api。

最新更新