Represents a method that is called when a remote Security Support Provider Interface (SSPI) certificate is being validated.
This delegate is used with the SslStream.AuthenticateAsClient method.
public delegate bool ValidationCallback(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors
);
true if the certificate is valid; otherwise, false.
The ValidationCallback delegate is used to provide a custom implementation for validating an SSL/TLS certificate. When you call the SslStream.AuthenticateAsClient method, you can optionally provide a delegate to handle certificate validation. This allows you to enforce specific security policies, such as checking the certificate's issuer, subject name, or expiration date, beyond the default validation performed by the system.
If the remote endpoint's certificate has errors (indicated by the sslPolicyErrors parameter), your callback method can examine these errors and decide whether to trust the certificate. For example, you might choose to ignore certain errors in development environments but strictly enforce them in production.
If your callback method returns true, the authentication process continues. If it returns false, the authentication fails, and an exception is thrown.
using System;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Net.Sockets;
public class SslClient
{
public static void Main(string[] args)
{
try
{
TcpClient client = new TcpClient("example.com", 443);
SslStream sslStream = new SslStream(
client.GetStream(),
false,
new RemoteCertificateValidationCallback(ValidateServerCertificate),
null);
// The server name used to authenticate the server.
string serverName = "example.com";
sslStream.AuthenticateAsClient(serverName);
Console.WriteLine("SSL connection established.");
// Perform further operations with the sslStream...
sslStream.Close();
client.Close();
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
{
// Certificate is valid.
return true;
}
Console.WriteLine($"Certificate error: {sslPolicyErrors}");
// Do not allow this client to communicate with untrusted servers.
// In a production environment, you should consider carefully whether
// to allow connections to servers with certificate errors.
return false;
}
}
Namespace:System.Net.Security
Assembly:System.Net.Primitives (in .NET Core 3.0 and later), System (in .NET Framework)