Represents a callback method that is called when a remote certificate is validated.
public delegate bool RemoteCertValidationCallback(
object sender,
System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors
);
This delegate is used to create a callback method that receives the following parameters:
| Parameter | Description |
|---|---|
sender |
The object that initiated the callback. This is typically an instance of the SslStream class. |
certificate |
The X.509 certificate used by the remote end of the connection. |
chain |
The X.509 certificate chain associated with the remote certificate. |
sslPolicyErrors |
One or more errors that occurred when validating the remote certificate. |
true to allow the connection to continue; otherwise, false.
When you create a delegate instance of type RemoteCertValidationCallback, you must specify the method that the delegate will call. To associate the method with the delegate, just pass a reference to the method as an argument to the delegate constructor. For example, an instance of the delegate can be initialized with a method named ValidateServerCertificate.
The following example shows how to implement a callback method that is called when a remote certificate is validated.
public class SampleClient
{
public static bool ValidateServerCertificate(
object sender,
System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
// In a real-world scenario, you would inspect the certificate and the errors.
// For this example, we'll allow the connection if there are no SSL policy errors.
if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
{
return true;
}
// Log the errors for debugging.
Console.WriteLine("SSL Policy Errors: {0}", sslPolicyErrors);
// In this example, we are returning false for any policy errors.
// A more robust implementation might check specific error types or inspect the certificate details.
return false;
}
public static void ConnectToServer(string host, int port)
{
TcpClient client = new TcpClient(host, port);
SslStream sslStream = new SslStream(
client.GetStream(),
false,
new RemoteCertValidationCallback(ValidateServerCertificate),
null); // Client authentication is not used here.
try
{
sslStream.AuthenticateAsClient(host);
// Use the sslStream for secure communication...
}
catch (Exception ex)
{
Console.WriteLine("Authentication failed: {0}", ex.Message);
}
finally
{
sslStream.Close();
client.Close();
}
}
}
RemoteCertValidationCallback method to prevent man-in-the-middle attacks. Never blindly trust all certificates or ignore all errors in production environments.
System.Net.Security