如何:C#WebClient使用双向TLS访问服务端点(类似Oauth 2.0的协议)



我需要点击一个服务来获得应用票证,以便对另一个服务进行身份验证。解决方案托管在端点上。

我尝试在谷歌chrome中使用POSTMAN应用程序,它成功了,并返回了我的AppID。当我在POSTMAN应用程序中提交(POST)请求时,它会提示输入证书。当我选择正确的证书时,调用成功。

我需要在C#(在web应用程序中)中实现相同的功能

我尝试使用RestSharp.RestClient库,但不断出现以下错误:"在站点证书中找不到客户端证书"。

附上代码以供参考。


var client = new RestSharp.RestClient("MyUrl");
var request = new RestSharp.RestRequest("pksecure/oauth20_clientcredentials.srf", RestSharp.Method.POST);
request.AddParameter("grant_type", "client_credentials");
request.AddParameter("param2", "value2");
request.AddParameter("scope", "machinename");
client.ClientCertificates = new System.Security.Cryptography.X509Certificates.X509CertificateCollection();
client.ClientCertificates.Add(new System.Security.Cryptography.X509Certificates.X509Certificate(
    @"E:MyCertificate.pfx"
    , "MyPassword"
    ));
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
        delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslError)
        {
            bool validationResult = true;
            return validationResult;
        };

var response = client.Execute(request);
var content = response.Content; // raw content as string

请。帮助使用双向TLS进行此调用。

TIA,类似

我不知道为什么我不能使用RestSharp完成它。

但是我可以使用HttpWebRequest来实现它。

此外,早些时候我使用了导致错误的Certificate.Pfx文件。使用证书.Cer文件解决了此问题。

张贴代码以供参考:

var request = (HttpWebRequest)WebRequest.Create("MyURL/oauth20_clientcredentials.srf");
var postData = "grant_type=client_credentials";
postData += "&param2=value2";
postData += "&scope=" + HttpUtility.UrlEncode("machinename");
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}
request.ClientCertificates.Add(new System.Security.Cryptography.X509Certificates.X509Certificate(@"E:MyCertificate.cer"));
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
return appToken;

谢谢,

Sam Jayander Thiagarajan。

最新更新