System.Net.Security.CertificatePolicy Class

Table of Contents

Overview

The CertificatePolicy class is an abstract class that defines the interface for applications to implement custom certificate validation policies for SslClientAuthenticationOptions and SslServerAuthenticationOptions when using the System.Net.Security.SslStream class.

This class is fundamental for scenarios requiring fine-grained control over how SSL/TLS certificates are validated, such as trusting specific certificate authorities, checking certificate revocation, or applying custom business logic to the validation process.

Syntax

public abstract class CertificatePolicy

Inheritance Hierarchy

System.Object
    System.Net.Security.CertificatePolicy

Members

Constructors

There are no public constructors for this abstract class.

Methods

The CertificatePolicy class has one abstract method:

public abstract bool CheckValidationResult(
    string hostName,
    System.Security.Cryptography.X509Certificates.X509Certificate certificate,
    System.Security.Cryptography.X509Certificates.X509Chain chain,
    System.Net.Security.SslPolicyErrors sslPolicyErrors
);

Parameters

Returns

true if the server certificate is trusted; otherwise, false.

Remarks

Code Example

The following example demonstrates how to create a custom CertificatePolicy that trusts any certificate presented by a specific server, regardless of its validity. Note: This is for demonstration purposes only and should not be used in production environments as it bypasses critical security checks.

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

public class MyCustomCertificatePolicy : CertificatePolicy
{
    public override bool CheckValidationResult(
        string hostName,
        X509Certificate certificate,
        X509Chain chain,
        SslPolicyErrors sslPolicyErrors
    )
    {
        // In a real-world scenario, you would implement robust validation logic here.
        // For example, check if sslPolicyErrors is SslPolicyErrors.None
        // or if the certificate is issued by a trusted authority.

        if (sslPolicyErrors == SslPolicyErrors.None)
        {
            return true;
        }

        // Example: Log errors for debugging purposes
        Console.WriteLine("SSL Policy Error encountered for host {0}: {1}", hostName, sslPolicyErrors);

        // For this example, we'll trust the connection if there are policy errors (NOT RECOMMENDED FOR PRODUCTION)
        return true;
    }
}

// To use this policy:
// SslClientAuthenticationOptions options = new SslClientAuthenticationOptions();
// options.RemoteCertificateValidationCallback = new MyCustomCertificatePolicy().CheckValidationResult;
// SslStream sslStream = new SslStream(innerStream, false, options);

See Also