Pages

Tuesday, October 16, 2018

HttpClient, Web API REST service and self signed Certificates

I recently came up with the problem where my web API was hosted locally on IIS using self signed certificate. 

The same code was working absolutely fine in Production, but for local, it was throwing exception because locally I had installed a self signed IIS Express certificate.

Here is the exception that I received (in full)...

System.AggregateException
  HResult=0x80131500
  Message=One or more errors occurred.
  Source=mscorlib
  StackTrace:
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at ..............
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.b__c(Object instance, Object[] methodParameters)
   at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)
Inner Exception 1:
HttpRequestException: An error occurred while sending the request.
Inner Exception 2:
WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
Inner Exception 3:
AuthenticationException: The remote certificate is invalid according to the validation procedure.

The only help that I got from the exception was from Inner Exception 3: AuthenticationException: The remote certificate is invalid according to the validation procedure.

So, to look into the details, I realized that the Self Signed Certificate from my local IIS is causing the problem. After a bit more googling I came up with this solution.


 #if DEBUG  
         //Accept all server certificate  
         ServicePointManager.ServerCertificateValidationCallback =  
           delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)  
           {  
             return true;  
           };  
 #endif  

Notice the #if DEBUG to make sure that the self signed certificate only works in case of local development environment only.

This sorted out the issue as now, I was bypassing the Certificate check using my own delegate.

No comments:

Post a Comment