MSDN Search

CertificateValidationCallback

Overview

The CertificateValidationCallback delegate represents a method that validates a server's SSL certificate during an SSL/TLS handshake. It is used by classes such as SslStream to allow custom certificate validation logic.

Syntax

public delegate bool CertificateValidationCallback(
    object sender,
    X509Certificate certificate,
    X509Chain chain,
    SslPolicyErrors sslPolicyErrors
);

Parameters

NameTypeDescription
senderobjectThe object that is invoking the callback.
certificateX509CertificateThe certificate presented by the remote party.
chainX509ChainThe chain of certificate authorities associated with the certificate.
sslPolicyErrorsSslPolicyErrorsAny SSL policy errors detected during the handshake.

Return Value

Returns true to accept the certificate; false to reject it.

Remarks

The delegate is typically assigned to the SslStream.CertificateValidationCallback property. Implementations can perform additional checks such as hostname validation, revocation status, or custom trust lists.

Example

using System;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

class Program
{
    static void Main()
    {
        var client = new TcpClient("example.com", 443);
        var stream = new SslStream(client.GetStream(), false, ValidateServerCertificate);
        stream.AuthenticateAsClient("example.com");
    }

    public static bool ValidateServerCertificate(
        object sender,
        X509Certificate certificate,
        X509Chain chain,
        SslPolicyErrors sslPolicyErrors)
    {
        // Accept self‑signed certificates for testing only.
        if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors &&
            chain.ChainStatus[0].Status == X509ChainStatusFlags.UntrustedRoot)
        {
            return true;
        }

        return sslPolicyErrors == SslPolicyErrors.None;
    }
}