使用C#的证书进行SSL客户端身份验证

编程入门 行业动态 更新时间:2024-10-25 14:29:36
本文介绍了使用C#的证书进行SSL客户端身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要创建一个c#应用程序,该应用程序必须使用SSL向服务器发送API请求.我需要创建客户端身份验证.我已经有服务器CA证书,客户端证书(cer),客户端私钥(pem)和密码.我找不到有关如何创建客户端连接的示例.有人可以建议我从小代码开始的地方很好解释吗?我手上有客户证书(PEM),客户提供密钥和客户密钥的密码.我不知道从哪里开始编写代码以向服务器发送请求

I need to create a c# application that has to send API request to a server using SSL. I need to create the Client authentication. I already have the server CA certificate, the client certificate (cer), the client private key (pem) and passphrase. I can't find an example on how to create the client connection. Can someone suggest me where to start with a small code well explained? In my hand I have the client certificate (PEM), the Client Provate Key and the Passphrase for the Client Key. I have no idea where to start to write the code to send a request to the server

推荐答案

前一段时间,我创建了此POC 用于在.Net Core中使用证书进行客户端身份验证.它使用 idunno.Authentication 程序包现在 .Net Core中的内置.我的POC现在可能有点过时了,但这对您来说可能是一个很好的起点.

Some time ago I've created this POC for client authentication with certificate in .Net Core. It uses idunno.Authentication package that is now build-in in .Net Core. My POC probably is bit outdated now, but it can be a good starting point for you.

首先创建一个扩展方法,以将证书添加到 HttpClientHandler :

First create an extension method to add certificate to HttpClientHandler:

public static class HttpClientHandlerExtensions { public static HttpClientHandler AddClientCertificate(this HttpClientHandler handler, X509Certificate2 certificate) { handler.ClientCertificateOptions = ClientCertificateOption.Manual; handler.ClientCertificates.Add(certificate); return handler; } }

然后是将证书添加到 IHttpClientBuilder

public static IHttpClientBuilder AddClientCertificate(this IHttpClientBuilder httpClientBuilder, X509Certificate2 certificate) { httpClientBuilder.ConfigureHttpMessageHandlerBuilder(builder => { if (builder.PrimaryHandler is HttpClientHandler handler) { handler.AddClientCertificate(certificate); } else { throw new InvalidOperationException($"Only {typeof(HttpClientHandler).FullName} handler type is supported. Actual type: {builder.PrimaryHandler.GetType().FullName}"); } }); return httpClientBuilder; }

然后加载证书并在 HttpClientFactory

var cert = CertificateFinder.FindBySubject("your-subject"); services .AddHttpClient("ClientWithCertificate", client => { client.BaseAddress = new Uri(ServerUrl); }) .AddClientCertificate(cert);

现在,当您使用由工厂创建的客户端时,它将自动发送带有请求的证书;

Now when you will use client created by factory it will automatically send your certificate with the request;

public async Task SendRequest() { var client = _httpClientFactory.CreateClient("ClientWithCertificate"); .... }

更多推荐

使用C#的证书进行SSL客户端身份验证

本文发布于:2023-11-10 01:11:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573950.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:身份验证   客户端   证书   SSL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!