[英]C#, .Net Core Private key authentication httpClient
We are having a problem with a friend with loading a private certificate to httpHandler. 我们在向httpHandler加载私有证书的朋友遇到问题。
We are using .net core and need to host all aplication in the cloud. 我们正在使用.net核心,需要在云端托管所有应用程序。
Main goal is to get message from SQS and perform some specified API shots after with consumed data. 主要目标是从SQS获取消息,并在消耗数据后执行一些指定的API镜头。
We have a problem with certificate with public / private key. 使用公钥/私钥的证书存在问题。 We have tried I think all the possible ways of loading it.
我们已经尝试了所有可能的加载方法。
public async Task<HttpResponseMessage> VisitHttps()
{
// Proceed for an invalid cerficate
ServicePointManager.ServerCertificateValidationCallback +=
(sender, certificate, chain, sslPolicyErrors) => true;
// Add the certificate
var handler = new HttpClientHandler();
var cert = GetMyCert();
if (cert != null)
{
handler.ClientCertificates.Add(cert);
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
//handler.PreAuthenticate = true;
}
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
HttpClient cclient = new HttpClient(handler)
{
//BaseAddress = new Uri("https://someurl.com")
};
cclient.DefaultRequestHeaders.Accept.Clear();
cclient.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
return await cclient.GetAsync("https://some-url.com/ping"); }
And the method GetMyCert() looks like below: GetMyCert()方法如下所示:
string currentLocation = $"{AppDomain.CurrentDomain.BaseDirectory}key-public.crt";
//var xcert = new X509Certificate2(currentLocation, "password");
////var currentLocationPriv = $"{AppDomain.CurrentDomain.BaseDirectory}key-private.crt";
////var privcert = new X509Certificate2(currentLocationPriv, "password", X509KeyStorageFlags.EphemeralKeySet);
//var certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
//certStore.Open(OpenFlags.ReadWrite);
//certStore.Add(xcert);
//certStore.Close();
//return xcert;
X509Store store = new X509Store("My", StoreLocation.CurrentUser);
X509Certificate2 cert;
cert = new X509Certificate2(File.ReadAllBytes(currentLocation), "password", X509KeyStorageFlags.MachineKeySet);
bool result = cert.Verify();
var r2 = result;
return cert;
commented lines are variances of what we have tried to do. 评论的行是我们试图做的差异。
We have no idea what else we should try to handle this issue. 我们不知道我们还应该尝试处理这个问题。
Any guidelines would be more than welcome 任何指导方针都非常受欢迎
EDIT: 编辑:
I've tried registering this inside startup class but it seems not working anyway. 我已经尝试在启动类中注册这个但是它似乎无论如何都没有用。 I always got the private key field inside certificate empty.
我总是将证书中的私钥字段清空。 And hasPrivateKey marked as false.
并且hasPrivateKey标记为false。
private void CreateCert(IServiceCollection services)
{
string currentLocation = $"{AppDomain.CurrentDomain.BaseDirectory}key-public.crt";
var certificate = new X509Certificate2(currentLocation, "password");
services.AddHttpClient("TestClient", client =>
{
client.BaseAddress = new Uri("https://someurl.com");
})
.ConfigurePrimaryHttpMessageHandler(() =>
{
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(certificate);
return handler;
});
}
My Test code: 我的测试代码:
[Fact]
public async Task ShouldPong()
{
var testClient = new TestClient()
{
BaseAddress = new Uri("https://someurl.com")
};
var result = await testClient.GetAsync("/ping");
result.StatusCode.Should().Be(HttpStatusCode.OK);
}
TestClient: TestClient的:
public class TestClient : HttpClient
{
public TestClient()
:base()
{
}
public TestClient(HttpMessageHandler handler)
: base(handler)
{
}
}
EDIT: 编辑:
The problem was solved when changing the .crt files into a .pfx file. 将.crt文件更改为.pfx文件时,问题得以解决。 Since the API we was hitting was hosted on nginx.
由于我们正在点击的API是在nginx上托管的。
The problem was resolved by creating a .PFX file. 通过创建.PFX文件解决了该问题。 The server we were hitting was hosted on nginx that requires .pfx format.
我们所服务的服务器托管在需要.pfx格式的nginx上。 The .crt files are PEM certificate that was not valid for nginx.
.crt文件是对nginx无效的PEM证书。
I think you're not instantiating the client correctly, accordingly with the doc for Named Clients . 我认为您没有正确地实例化客户端,因此使用命名客户端的文档。
You will need to receive the IHttpClientFactory in run-time and ask for your named client like this: 您需要在运行时接收IHttpClientFactory并请求您的命名客户端,如下所示:
var client = _clientFactory.CreateClient("TestClient");
About testing with Dependency Injection, I believe this Microsoft tutorial can help: Integration Tests Asp.Net Core . 关于使用依赖注入进行测试,我相信这个Microsoft教程可以提供帮助: 集成测试Asp.Net Core 。 The deal here is, as the Startup.cs file and the Core Dependency Injector are part of the framework, you need to setup simulate the web application in the test context.
这里的交易是,由于Startup.cs文件和Core Dependency Injector是框架的一部分,您需要在测试环境中设置模拟Web应用程序。 And Microsoft provides the WebApplicationFactory for that.
Microsoft为此提供了WebApplicationFactory。
This example demonstrate a test with a httpClient given by the IHttpClientFactory in a simulated web application environment. 此示例演示了在模拟Web应用程序环境中使用IHttpClientFactory给出的httpClient进行的测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.