Microsoft Docs

ValidationContext Class

Microsoft.MsNet.Security
Provides context information to a certificate validation callback.

API Summary

Properties

ChainContext

public X509ChainContext ChainContext { get; }

Gets the X.509 chain context. This object contains the X.509 chain and information about the validation process.

TargetHost

public string TargetHost { get; }

Gets the name of the server to which the client is connecting.

AllowUnknownCertificateAuthority

public bool AllowUnknownCertificateAuthority { get; set; }

Gets or sets a value indicating whether to allow certificates issued by an unknown certificate authority. The default is false.

AllowSslPolicyErrors

public SslPolicyErrors AllowSslPolicyErrors { get; set; }

Gets or sets a value indicating which SSL policy errors are allowed. The default is SslPolicyErrors.None.

Constructors

ValidationContext

public ValidationContext(X509ChainContext chainContext, string targetHost)

Initializes a new instance of the ValidationContext class with the specified X.509 chain context and target host name.

Parameters

  • chainContext: An X509ChainContext object that contains the X.509 chain and validation information.
  • targetHost: The name of the server to which the client is connecting.
Methods

ValidateCertificate

public bool ValidateCertificate()

Performs certificate validation based on the current properties of the ValidationContext object.

Returns: true if the certificate is valid; otherwise, false.

Exceptions

  • ArgumentNullException: chainContext is null.
  • ArgumentException: targetHost is null or an empty string.
Remarks

The ValidationContext class is used in conjunction with the RemoteCertValidationCallback delegate. When an SSL/TLS connection is established, the .NET framework may call this delegate to determine whether to trust the server's certificate.

The ValidationContext object provides information about the server's certificate chain and the target host. You can use its properties to configure the validation process, such as specifying which certificate authorities are trusted or which SSL policy errors are acceptable.

The ValidateCertificate method allows you to programmatically perform the validation based on the context provided. This is useful when implementing custom certificate validation logic.

Examples

Custom Certificate Validation Callback


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

public class CertificateValidator
{
    public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        // Create a ValidationContext from the provided information
        X509ChainContext chainContext = new X509ChainContext(chain, certificate);
        string targetHost = ((System.Net.Http.HttpClient)sender).DefaultRequestHeaders.Host; // Example: getting host from HttpClient

        ValidationContext validationContext = new ValidationContext(chainContext, targetHost);

        // Optionally, customize validation rules
        validationContext.AllowSslPolicyErrors = SslPolicyErrors.RemoteCertificateChainErrors | SslPolicyErrors.RemoteCertificateNameMismatch;
        validationContext.AllowUnknownCertificateAuthority = true;

        // Perform validation using the context
        bool isValid = validationContext.ValidateCertificate();

        if (!isValid)
        {
            Console.WriteLine($"Certificate validation failed for host: {targetHost}");
            // Log detailed errors from chainContext if needed
        }

        return isValid;
    }

    // Example usage with HttpClient
    public static void UseCustomValidator()
    {
        var httpClientHandler = new System.Net.Http.HttpClientHandler
        {
            ServerCertificateCustomValidationCallback = ValidateServerCertificate
        };

        using (var httpClient = new System.Net.Http.HttpClient(httpClientHandler))
        {
            try
            {
                var response = httpClient.GetAsync("https://your-secure-site.com").Result;
                response.EnsureSuccessStatusCode();
                Console.WriteLine("Successfully connected!");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }
    }
}