Exception: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel

Bhhruguni picture Bhhruguni · Jan 7, 2017 · Viewed 21.3k times · Source

for firebase notification code

WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send"); 
tRequest.Method = "post";
tRequest.ContentType = "application/json";
var data = new{collapse_key = "unassigned", to = deviceToken,data = new
  {body = message,title = title,sound = "default"}
};

message to pass for notifaction on mobile

var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationId));
tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
tRequest.ContentLength = byteArray.Length;

error occur here below code

using (Stream dataStream = tRequest.GetRequestStream())
{ 
  dataStream.Write(byteArray, 0, byteArray.Length);
 using (WebResponse tResponse = tRequest.GetResponse())
  { 
    using (Stream dataStreamResponse = tResponse.GetResponseStream())
    { 

   //code 1
    }     
  }   
}  

Answer

Pablo Recalde picture Pablo Recalde · Jan 7, 2017

The exception in the title says that you are connecting to an endpoint with TLS encryption, and the certificate exposed by that endpoint is not trusted by you. This means that is not signed with a certificate that you have in your CA (Certificate Authority) Store. Like a self-signed certificate.

If the certificate is self signed, you can add it to your CA Store. If not, you can try to navigate the endpoint with your browser, and look for a copy of the certificate that the endpoint is presenting, to manually trust it. (Beware that by doing this if the endpoint has been already compromised you're manually trusting its certificate.)

You can also avoid this check by adding a custom certificate validation handler that always returns valid! (true). But, please be aware that doing this will expose you to man-in-the-middle attacks, as you'll loose the ability to check the endpoints authenticity.

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