Wednesday, April 8, 2020

X++ code Ignore SSL certificate validation d365 f&o


Ignore SSL certificate validation while calling api from d365 finance and operations

It is a common thing that some of your application functionalities depend on an external HTTPS endpoint. However, renewal of SSL certificate for the external party is out of your control and you have to rely on the third party that certificate will be renewed on time. If renewal does not happen on time, SSL certificate becomes invalid.Third party may not have valid SSL certificate for DEV/UAT environments.
.NET has by default build in mechanism to throw an exception if you are trying to make a web request to HTTPS endpoint which has invalid SSL certificate. In other words, .NET is doing SSL certificate validation for you under the hood.
The exception that you get is:
"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."

Even if you try to access the URL to which you are trying to create a request in a browser you will get the following screen



You can resolve this issue by adding a custom validation method

private boolean validateCert(System.Object sender,X509Certificate    cert, X509Chain chain, SslPolicyErrors errors)
   {
       return true;
   }
In this example, validation method is overridden by custom method which always returns true value.
So before making a request, declare this callback method as shown below:

Private void apiCallMethod()
{
System.Net.Security.RemoteCertificateValidationCallback callBack;
       callBack += eventhandler(this.validateCert);       
       ServicePointManager::ServerCertificateValidationCallback = callBack;
System.Net.WebRequest           webreq = System.Net.WebRequest::Create(“api_url”);
Webreq.GetResponse();
}

This way, validation will always pass as your custom method always returns true value.
Thank you for reading,..!!!!

1 comment:

  1. It took me a long time to find the answer to this question. I'm very glad to find your solution, which has been proved to be effective. Thank you very much for sharing. Now post my code.

    boolean validateCert(System.Object sender,
    System.Security.Cryptography.X509Certificates.X509Certificate cert,
    System.Security.Cryptography.X509Certificates.X509Chain chain,
    System.Net.Security.SslPolicyErrors errors)
    {
    return true;
    }

    ====
    System.Net.Security.RemoteCertificateValidationCallback callBack;
    callBack += eventhandler(this.validateCert);
    System.Net.ServicePointManager::ServerCertificateValidationCallback = callBack;

    ReplyDelete