英語で読む

次の方法で共有


RemoteCertificateValidationCallback 代理人

定義

認証に使用されるリモートの SSL (Secure Sockets Layer) 証明書を検証します。

C#
public delegate bool RemoteCertificateValidationCallback(object sender, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors sslPolicyErrors);
C#
public delegate bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors);

パラメーター

sender
Object

この検証のステータス情報を格納するオブジェクト。

certificate
X509Certificate

リモート側の認証に使用される証明書。

chain
X509Chain

リモートの証明書に関連付けられた証明機関のチェーン。

sslPolicyErrors
SslPolicyErrors

リモートの証明書に関連付けられた 1 つ以上のエラー。

戻り値

指定した証明書が認証に使用できるかどうかを判断する Boolean 値。

次のコード例では、 クラスのインスタンスによって呼び出されるメソッドを RemoteCertificateValidationCallback 実装します。 検証エラーがある場合、このメソッドはそれらを表示し、 を返 falseします。これにより、認証されていないサーバーとの通信が禁止されます。

C#

// The following method is invoked by the RemoteCertificateValidationDelegate.
public static bool ValidateServerCertificate(
      object sender,
      X509Certificate certificate,
      X509Chain chain,
      SslPolicyErrors sslPolicyErrors)
{
   if (sslPolicyErrors == SslPolicyErrors.None)
        return true;

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

    // Do not allow this client to communicate with unauthenticated servers.
    return false;
}

次のコード例では、前のコード例で定義した メソッドを使用してデリゲートを作成します。

C#
// Create a TCP/IP client socket.
// machineName is the host running the server application.
TcpClient client = new TcpClient(machineName,5000);
Console.WriteLine("Client connected.");
// Create an SSL stream that will close the client's stream.
SslStream sslStream = new SslStream(
    client.GetStream(),
    false,
    new RemoteCertificateValidationCallback (ValidateServerCertificate),
    null
    );
// The server name must match the name on the server certificate.
try
{
    sslStream.AuthenticateAsClient(serverName);
}
catch (AuthenticationException e)
{
    Console.WriteLine("Exception: {0}", e.Message);
    if (e.InnerException != null)
    {
        Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
    }
    Console.WriteLine ("Authentication failed - closing the connection.");
    client.Close();
    return;
}

注釈

デリゲートの引数には、クライアントまたはサーバーの sslPolicyErrors 認証中に SSPI によって返された証明書エラーが含まれます。 Booleanこのデリゲートによって呼び出されたメソッドによって返される値によって、認証が成功するかどうかが決まります。

このデリゲートは、 クラスで使用されます SslStream

拡張メソッド

GetMethodInfo(Delegate)

指定したデリゲートによって表されるメソッドを表すオブジェクトを取得します。

適用対象

製品 バージョン
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

こちらもご覧ください