.NET API Documentation

System.Net.Security

SSLServerAuthenticationOptions Class

Provides options for authenticating an SSL/TLS server.

Summary

The SSLServerAuthenticationOptions class is used to configure the server-side authentication process for an SSL/TLS connection. It allows you to specify details such as the certificate used for authentication, revocation checking, and trusted certificate authorities.

Properties

Name Type Description
ClientCertificateRequired bool Gets or sets a value that indicates whether the client certificate is required. If true, the client must present a certificate.
CertificateRevocationCheckMode System.Security.Cryptography.X509Certificates.X509RevocationFlag Gets or sets the revocation checking mode for the client certificate.
LocalCertificateSelectionCallback System.Net.Security.LocalCertificateSelectionCallback Gets or sets a delegate that is called when the server needs to select a certificate to present to the client.
RemoteCertificateValidationCallback System.Net.Security.RemoteCertificateValidationCallback Gets or sets a delegate that is called to validate the certificate presented by the client.
ServerCertificate System.Security.Cryptography.X509Certificates.X509Certificate2 Gets or sets the server certificate used for authentication.
EncryptionPolicy System.Net.Security.EncryptionPolicy Gets or sets the encryption policy for the SSL/TLS connection.

Remarks

When establishing an SSL/TLS connection as a server, you need to provide credentials to identify yourself to the client. The SSLServerAuthenticationOptions class encapsulates these credentials and related settings. You typically instantiate this class and set its properties before passing it to a method like SslStream.AuthenticateAsServerAsync.

The ServerCertificate property is crucial for server authentication. If not provided, the system may attempt to find a suitable certificate, but explicit configuration is recommended for robustness.

The callbacks LocalCertificateSelectionCallback and RemoteCertificateValidationCallback offer fine-grained control over certificate selection and validation, respectively. These are particularly useful in scenarios where you need to dynamically choose a certificate based on client information or perform custom validation logic.

Example Usage

The following example demonstrates how to create and configure SSLServerAuthenticationOptions for a server:

using System;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Net.Sockets;
using System.Threading.Tasks;

public class SslServerExample
{
    public static async Task StartServerAsync(int port)
    {
        var listener = new TcpListener(System.Net.IPAddress.Any, port);
        listener.Start();
        Console.WriteLine($"Server started on port {port}. Listening for connections...");

        while (true)
        {
            TcpClient client = await listener.AcceptTcpClientAsync();
            _ = HandleClientAsync(client); // Fire and forget
        }
    }

    private static async Task HandleClientAsync(TcpClient tcpClient)
    {
        using (var sslStream = new SslStream(tcpClient.GetStream(), false))
        {
            try
            {
                // Load the server certificate (replace with your actual certificate path and password)
                var serverCertificate = new X509Certificate2("path/to/your/server.pfx", "your_password");

                // Configure SSL server authentication options
                var authOptions = new SslServerAuthenticationOptions
                {
                    ServerCertificate = serverCertificate,
                    ClientCertificateRequired = false, // Set to true if client cert is mandatory
                    EncryptionPolicy = EncryptionPolicy.RequireEncryption // Or EncryptionPolicy.AllowNoEncryption for testing
                };

                // Authenticate the server
                await sslStream.AuthenticateAsServerAsync(authOptions);
                Console.WriteLine("Client connected and SSL handshake successful.");

                // Now you can read from and write to the sslStream
                // ...

                // Example: Echo back received data
                byte[] buffer = new byte[1024];
                int bytesRead = await sslStream.ReadAsync(buffer, 0, buffer.Length);
                if (bytesRead > 0)
                {
                    string receivedMessage = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
                    Console.WriteLine($"Received: {receivedMessage}");

                    byte[] response = System.Text.Encoding.UTF8.GetBytes($"Echo: {receivedMessage}");
                    await sslStream.WriteAsync(response, 0, response.Length);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error handling client: {ex.Message}");
            }
            finally
            {
                sslStream.Close(); // Closes the underlying stream as well
                tcpClient.Close();
            }
        }
    }
}

See Also