SslStream.BeginAuthenticate Method

In System.Net.Security namespace
Defined in mscorlib.dll

Initiates an asynchronous request to authenticate the remote party. This method does not block the calling thread.

Syntax

public IAsyncResult BeginAuthenticate(
    AsyncCallback callback,
    object state
)

Parameters

Name Type Description
callback System.AsyncCallback An AsyncCallback delegate that references the method to call when the operation is complete.
state object A user-defined object that contains state information for the asynchronous operation. This parameter can be null.

Return Value

Type Description
System.IAsyncResult An IAsyncResult object that represents the status of the asynchronous operation.

Remarks

Call EndAuthenticate to complete the asynchronous operation. The IAsyncResult object returned by BeginAuthenticate must be passed to EndAuthenticate.

The BeginAuthenticate method is used to initiate the TLS/SSL handshake. This handshake establishes a secure channel between the client and server. The AsyncCallback delegate is invoked upon completion of the handshake, allowing for non-blocking operations.

If the handshake fails, an exception is thrown.

Requirements

Platform Supported
.NET Framework Supported in versions 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.6, 4.7, 4.8.
.NET Standard Supported in versions 1.3, 1.4, 2.0.
.NET Core Supported in versions 1.0, 1.1, 2.0, 2.1, 2.2, 3.0, 3.1.
Mono Supported.
Xamarin Supported.
UWP Supported.

Example

The following code example demonstrates how to use the BeginAuthenticate method to initiate an asynchronous SSL handshake.

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

public class SslClient
{
    private TcpClient client;
    private SslStream sslStream;
    private X509Certificate serverCertificate;

    public SslClient(TcpClient tcpClient, X509Certificate certificate)
    {
        client = tcpClient;
        serverCertificate = certificate;
        sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
    }

    public void StartAuthentication()
    {
        try
        {
            Console.WriteLine("Attempting to authenticate...");
            // Initiate the asynchronous authentication process
            IAsyncResult result = sslStream.BeginAuthenticate(
                new AsyncCallback(AuthenticationCallback),
                null // state object
            );

            // You can perform other tasks here while authentication is in progress
            Console.WriteLine("Authentication initiated. Performing other tasks...");
            Thread.Sleep(100); // Simulate doing other work
            Console.WriteLine("Other tasks completed.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Authentication failed: {ex.Message}");
        }
    }

    private void AuthenticationCallback(IAsyncResult ar)
    {
        try
        {
            sslStream.EndAuthenticate(ar);
            Console.WriteLine("Authentication completed successfully.");

            // Now you can read/write to the secure stream
            // For example:
            // byte[] buffer = new byte[2048];
            // int bytesRead = sslStream.Read(buffer, 0, buffer.Length);
            // Console.WriteLine($"Received: {System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead)}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Authentication failed during EndAuthenticate: {ex.Message}");
        }
    }

    // Callback to validate the server certificate
    public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        if (sslPolicyErrors == SslPolicyErrors.None)
            return true;

        Console.WriteLine($"Certificate error: {sslPolicyErrors}");

        // Do not allow this sample to communicate with an untrusted server.
        return false;
    }

    public void Close()
    {
        sslStream?.Close();
        client?.Close();
    }
}

// To run this example, you would need to set up a server and provide a valid certificate.
// Example usage (conceptual):
// TcpListener listener = new TcpListener(IPAddress.Any, 12345);
// listener.Start();
// TcpClient client = listener.AcceptTcpClient();
// X509Certificate cert = X509Certificate.CreateFromCertFile("server.cer"); // Load your server certificate
// SslClient sslClient = new SslClient(client, cert);
// sslClient.StartAuthentication();
// // ... (handle client communication)
// sslClient.Close();
// listener.Stop();

Note

This method is part of the asynchronous I/O pattern in .NET. It allows applications to remain responsive while waiting for network operations to complete.