gpt4 book ai didi

c# - 如何在 .net core 3.1 中的依赖注入(inject)设置之外向 IHttpClientFactory httpclient 添加证书?

转载 作者:行者123 更新时间:2023-12-05 06:19:19 33 4
gpt4 key购买 nike

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

如果我在 Startup.cs 中的依赖项注入(inject)期间尝试添加证书,则找不到证书。似乎 Startup.Configure 在加载所有证书之前运行(?)。

因此,我需要能够在 azure 函数本身内将证书加载到 httpclient。但是,IHttpClientFactory 似乎没有任何机制来改变 CreateClient 创建的客户端,除了一些 header 。我如何在稍后的某个时间点在调用堆栈中添加证书(这将通过 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 中失败。我成功地从我的 keystore 中获取了证书指纹,但它在我的 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 后没有加载,为什么我的本地商店中的所有证书都没有被提取,我该如何让它正常工作?

最佳答案

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

How to use ConfigurePrimaryHttpMessageHandler generic

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

关于c# - 如何在 .net core 3.1 中的依赖注入(inject)设置之外向 IHttpClientFactory httpclient 添加证书?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60854830/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com