2

Related articles but did not solve issue:


Summary

When trying to request in C# using basic HttpWebRequest, returns error:

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel., System.Security.Authentication.A uthenticationException: The remote certificate is invalid according to the validation procedure.

But when using Postman to request on third-party API, returns success.


actual code:

Console.WriteLine("---START---");

var url = "https://" + ConfigurationManager.AppSettings["ClientDNS"].ToString() + ConfigurationManager.AppSettings["ClientTokenUri"].ToString();
var redirect = ConfigurationManager.AppSettings["UserRedirect"].ToString();
var clientId = ConfigurationManager.AppSettings["ClientId"].ToString();
var code = ConfigurationManager.AppSettings["ClientCode"].ToString();
var result = "";

Console.WriteLine(string.Format("url : {0}\n", url));
Console.WriteLine(string.Format("redirect : {0}\n", redirect));
Console.WriteLine(string.Format("clientid : {0}\n", clientId));
Console.WriteLine(string.Format("code : {0}\n", code));

try
{
    ServicePointManager.Expect100Continue = true;
    ServicePointManager.DefaultConnectionLimit = 9999;
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls 
        | SecurityProtocolType.Tls11 
        | SecurityProtocolType.Tls12 
        | SecurityProtocolType.Tls13
        | SecurityProtocolType.Ssl3;

    //As suggested by Ali Bahrami
    ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

    var postData = "grant_type=authorization_code&redirect_uri=" + redirect + "&code=" + code + "&client_id=" + clientId;

    var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    // Update base from link 01
    httpWebRequest.Method = "POST";
    httpWebRequest.AllowAutoRedirect = true;
    httpWebRequest.Timeout = 20 * 1000;
    httpWebRequest.ContentType = "application/x-www-form-urlencoded";
    httpWebRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
    httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36";

    byte[] buffer = Encoding.Default.GetBytes(postData);
    if (buffer != null)
    {
        httpWebRequest.ContentLength = buffer.Length;
        httpWebRequest.GetRequestStream().Write(buffer, 0, buffer.Length);
    }

    Console.WriteLine("getting response");
    var response = (HttpWebResponse)httpWebRequest.GetResponse();
    result = string.Format("result: {0}\n", new StreamReader(response.GetResponseStream()).ReadToEnd());

}

catch (Exception ex)
{
    result = string.Format("result: {0}\n", ex.Message + (ex.InnerException != null ? ", " + ex.InnerException : ""));
}

when using C# code

when using Postman

link 01 - https://stackoverflow.com/a/41970776/8975971

JCR10
  • 69
  • 1
  • 1
  • 7
  • 1
    Could you post `ServerCertificateValidationCallback` code as well? – Ali Bahrami Jun 11 '19 at 05:02
  • @AliBahrami - should i try this answer? https://stackoverflow.com/a/6613434/1665777 – JCR10 Jun 11 '19 at 05:03
  • I think `ServerCertificateValidationCallback ` is the key to solve your problem, share it with us. – Ali Bahrami Jun 11 '19 at 05:06
  • @AliBahrami - adding ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; gave 400 bad request. when checking parameters in postman vs in code, format is the same. kindly see [var postData] in actual code. – JCR10 Jun 11 '19 at 05:26
  • @AliBahrami - please post your comment to tag as the answer. Thank you! – JCR10 Jun 11 '19 at 05:37

1 Answers1

2

I think due to using self-signed certificate, ServicePointManagerServer cannot validate your certificate. As I suggested in the comments you need to write a method to change this behaviour in your case.

One of the workarounds is to return true whenever validation happened:

ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

Of course, some people don't approve this workaround in real-world cases because you are actually disabling the certificate validation. BUT if you are dealing with internal web services just use the method above to ignore the validation.

Ali Bahrami
  • 4,997
  • 3
  • 28
  • 45