. net客户端身份验证设置使用HttpWebRequest
本文关键字:HttpWebRequest 设置 客户端 身份验证 net | 更新日期: 2023-09-27 18:12:56
这更多的是关于如何让HttpWebRequest工作,甚至HttpWebRequest是正确的实现。在过去的几年里,我让我的c#和。net技能下降了,所以我希望我能原谅我。
我试图访问需要客户端身份验证的安全web服务。我有四个证书来打这个。
•根证书•中级根证书•设备证书•私钥
服务器是Java,这些证书是。jks格式的truststore和keystore。我把它们放到。pem文件中。
所以,我在c#客户端失败了,所以我想我应该写一个小的Python代码片段,以确保至少服务器端按预期工作。二十分钟后,我就能找到安全岗哨了。下面是代码:
# Keys
path = "C:''path''"
key = path + "device.pem"
privkey = path + "device_privkey.pem"
CACerts = path + "truststore.concat" # root & intermediate cert
def post():
url = "/url"
headers = {'Content-Type': 'application/xml'}
## This section is HTTPSConnection
context = ssl.SSLContext(ssl.PROTOCOL_TLS)
context.verify_mode = ssl.CERT_OPTIONAL
context.load_cert_chain(key, privkey, password='password')
context.verify_mode = ssl.CERT_NONE
context.load_verify_locations(CACerts)
conn = http.client.HTTPSConnection(host, port=8080, context=context)
conn.request("POST", url, registrationBody, headers)
response = conn.getresponse()
regresp = response.read()
连接证书是根证书和中间证书的连接。
你明白我的意思吗?现在我的c#/。净头痛。
这是我的尝试。我真不知道我在这儿干什么。 public async Task POSTSecure(string pathname, string body)
{
string path = "C:''path";
string key = path + "device.pem";
string privkey = path + "device_privkey.pem";
string CACerts1 = path + "vtn_root.pem";
string CACerts2 = path + "vtn_int.pem";
try
{
// Create certs from files
X509Certificate2 keyCert = new X509Certificate2(key);
X509Certificate2 rootCert = new X509Certificate2(CACerts1);
X509Certificate2 intCert = new X509Certificate2(CACerts2);
HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://" + host + ":" + port + pathname);
ServicePoint currentServicePoint = request.ServicePoint;
// build the client chain?
request.ClientCertificates.Add(keyCert);
request.ClientCertificates.Add(rootCert);
request.ClientCertificates.Add(intCert);
Console.WriteLine("URI: {0}", currentServicePoint.Address);
// This validates the server regardless of whether it should
request.ServerCertificateValidationCallback = ValidateServerCertificate;
request.Method = "POST";
request.ContentType = "application/xml";
request.ContentLength = body.Length;
using (var sendStream = request.GetRequestStream())
{
sendStream.Write(Encoding.UTF8.GetBytes(body), 0, body.Length);
}
var response = (HttpWebResponse)request.GetResponse();
}
catch (Exception e)
{
Console.WriteLine("Post error.");
}
}
感谢任何帮助或指针到一个体面的教程。
[编辑]更多信息。在服务器端,调试指向一个空的客户端证书链。
好的,我想我在最初的时候已经很接近了,但是我是这样解决的:
request.ClientCertificates = new X509Certificate2Collection(
new X509Certificate2(
truststore,
password));
"truststore"文件是一个。p12文件,包含上面列出的证书。可以通过keytool和openssl在。jks信任库的基础上创建。p12信任库。有很多关于如何做到这一点的信息