NegotiateStream クラス
アセンブリ: System (system.dll 内)
![構文](http://weblio.hs.llnwd.net/e7/img/dict/msdnc/minus.gif)
![解説](http://weblio.hs.llnwd.net/e7/img/dict/msdnc/minus.gif)
NegotiateStream クラスを使用して認証を行い、クライアントとサーバー間で送信される情報のセキュリティ保護を支援します。NegotiateStream を使用すると、次の操作を行うことができます。
情報を送信する前に、認証を行う必要があります。クライアントは、認証が完了するまでブロックする同期メソッドの AuthenticateAsClient、または認証の完了を待機する間ブロックしない非同期メソッドの BeginAuthenticateAsClient を使用して認証を要求します。サーバーは、同期メソッドの AuthenticateAsServer または非同期メソッドの BeginAuthenticateAsServer を使用して認証を要求します。クライアント (オプションでサーバー) は、Negotiate セキュリティ プロトコルを使用して認証されます。Windows 95 システムおよび Windows 98 システムの場合、認証に使用するプロトコルは Windows NT LAN Manager (NTLM) です。その他のプラットフォームでは、クライアントとサーバーの両方が Kerberos プロトコルをサポートしている場合、Kerberos が認証に使用されます。それ以外の場合は NTLM が使用されます。これらのプロトコルの詳細な説明については、http://msdn.microsoft.com/library/ にあるプラットフォーム SDK に関するドキュメントを参照してください。NegotiateStream クラスは、SSPI (Security Support Provider Interface) を使用して認証を実行します。
認証が成功したら、送信中のデータのセキュリティを保護するために、IsEncrypted プロパティと IsSigned プロパティをチェックして NegotiateStream で使用するセキュリティ サービスを確認する必要があります。相互認証が行われたかどうかを確認するには、IsMutuallyAuthenticated プロパティをチェックします。RemoteIdentity プロパティを使用して、リモート クライアントまたはリモート サーバーに関する情報を取得することもできます。
認証が失敗した場合、AuthenticationException または InvalidCredentialException を受け取ります。この場合は、異なる資格情報を使用して、認証を再試行できます。
データの送信には、同期メソッドの Write または非同期メソッドの BeginWrite を使用します。データの受信には、同期メソッドの Read または非同期メソッドの BeginRead を使用します。暗号化や署名などのセキュリティ サービスが有効化な場合、NegotiateStream によって、これらのサービスが自動的にデータに適用されます。
NegotiateStream は、NegotiateStream の作成時に提供するストリームを使用してデータを送信します。この基になるストリームを提供するときには、NegotiateStream を閉じたときに基になるストリームも閉じるかどうかを指定するオプションがあります。
![使用例](http://weblio.hs.llnwd.net/e7/img/dict/msdnc/minus.gif)
NegotiateStream を使用するクライアント サーバー接続のクライアント側のコード例を次に示します。クライアントは認証を行い、サーバーにメッセージを非同期的に送信します。
using System; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Text; namespace Examples.NegotiateStreamExample { public class ASynchronousAuthenticatingTcpClient { static TcpClient client = null; public static void Main(String[] args) { // Establish the remote endpoint for the socket. // For this example, use the local machine. IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost"); IPAddress ipAddress = ipHostInfo.AddressList[0]; // Client and server use port 11000. IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000); // Create a TCP/IP socket. client = new TcpClient(); // Connect the socket to the remote endpoint. client.Connect(remoteEP); Console.WriteLine("Client connected to {0}.", remoteEP.ToString()); // Ensure the client does not close when there is // still data to be sent to the server. client.LingerState = (new LingerOption(true, 0)); // Request authentication. NetworkStream clientStream = client.GetStream(); NegotiateStream authStream = new NegotiateStream(clientStream, false); // Pass the NegotiateStream as the AsyncState object // so that it is available to the callback delegate. IAsyncResult ar = authStream.BeginAuthenticateAsClient( new AsyncCallback(EndAuthenticateCallback), authStream ); Console.WriteLine("Client waiting for authentication..."); // Wait until the result is available. ar.AsyncWaitHandle.WaitOne(); // Display the properties of the authenticated stream. AuthenticatedStreamReporter.DisplayProperties(authStream); // Send a message to the server. // Encode the test data into a byte array. byte[] message = Encoding.UTF8.GetBytes("Hello from the client."); ar = authStream.BeginWrite(message, 0, message.Length, new AsyncCallback(EndWriteCallback), authStream); ar.AsyncWaitHandle.WaitOne(); Console.WriteLine("Sent {0} bytes.", message.Length); // Close the client connection. authStream.Close(); Console.WriteLine("Client closed."); } // The following method is called when the authentication completes. public static void EndAuthenticateCallback (IAsyncResult ar) { Console.WriteLine("Client ending authentication..."); NegotiateStream authStream = (NegotiateStream) ar.AsyncState; // End the asynchronous operation. authStream.EndAuthenticateAsClient(ar); // Console.WriteLine("AllowedImpersonation: {0}", authStream.AllowedImpersonation); } // The following method is called when the write operation completes. public static void EndWriteCallback (IAsyncResult ar) { Console.WriteLine("Client ending write operation..."); NegotiateStream authStream = (NegotiateStream) ar.AsyncState; // End the asynchronous operation. authStream.EndWrite(ar); } } // The following class displays the properties of an authenticatedStream. public class AuthenticatedStreamReporter { public static void DisplayProperties(AuthenticatedStream stream) { Console.WriteLine("IsAuthenticated: {0}", stream.IsAuthenticated); Console.WriteLine("IsMutuallyAuthenticated: {0}", stream.IsMutuallyAuthenticated); Console.WriteLine("IsEncrypted: {0}", stream.IsEncrypted); Console.WriteLine("IsSigned: {0}", stream.IsSigned); Console.WriteLine("IsServer: {0}", stream.IsServer); } } }
クライアント サーバー接続のクライアント側が NegotiateStream を使用してクライアントの認証およびクライアントから送信されたメッセージの読み取りを行うコード例を次に示します。
using System; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Security.Principal; using System.Text; using System.IO; using System.Threading; namespace Examples.NegotiateStreamExample { public class AsynchronousAuthenticatingTcpListener { public static void Main() { // Create an IPv4 TCP/IP socket. TcpListener listener = new TcpListener(IPAddress.Any, 11000); // Listen for incoming connections. listener.Start(); while (true) { TcpClient clientRequest = null; // Application blocks while waiting for an incoming connection. // Type CNTL-C to terminate the server. clientRequest = listener.AcceptTcpClient(); Console.WriteLine("Client connected."); // A client has connected. try { AuthenticateClient (clientRequest); } catch (Exception e) { Console.WriteLine(e); continue; } } } public static void AuthenticateClient(TcpClient clientRequest) { NetworkStream stream = clientRequest.GetStream(); // Create the NegotiateStream. NegotiateStream authStream = new NegotiateStream(stream, false); // Save the current client and NegotiateStream instance // in a ClientState object. ClientState cState = new ClientState(authStream, clientRequest); // Listen for the client authentication request. authStream.BeginAuthenticateAsServer ( new AsyncCallback(EndAuthenticateCallback), cState ); // Wait until the authentication completes. cState.Waiter.WaitOne(); cState.Waiter.Reset(); authStream.BeginRead(cState.Buffer, 0, cState.Buffer.Length, new AsyncCallback(EndReadCallback), cState); cState.Waiter.WaitOne(); // Finished with the current client. authStream.Close(); clientRequest.Close(); } // The following method is invoked by the // BeginAuthenticateAsServer callback delegate. public static void EndAuthenticateCallback (IAsyncResult ar) { // Get the saved data. ClientState cState = (ClientState) ar.AsyncState; TcpClient clientRequest = cState.Client; NegotiateStream authStream = (NegotiateStream) cState.AuthenticatedStream; Console.WriteLine("Ending authentication."); // Any exceptions that occurred during authentication are // thrown by the EndAuthenticateAsServer method. try { // This call blocks until the authentication is complete. authStream.EndAuthenticateAsServer(ar); } catch (AuthenticationException e) { Console.WriteLine(e); Console.WriteLine("Authentication failed - closing connection."); cState.Waiter.Set(); return; } catch (Exception e) { Console.WriteLine(e); Console.WriteLine("Closing connection."); cState.Waiter.Set(); return; } // Display properties of the authenticated client. IIdentity id = authStream.RemoteIdentity; Console.WriteLine("{0} was authenticated using {1}.", id.Name, id.AuthenticationType ); cState.Waiter.Set(); } public static void EndReadCallback(IAsyncResult ar) { // Get the saved data. ClientState cState = (ClientState) ar.AsyncState; TcpClient clientRequest = cState.Client; NegotiateStream authStream = (NegotiateStream) cState.AuthenticatedStream; // Get the buffer that stores the message sent by the client. int bytes = -1; // Read the client message. try { bytes = authStream.EndRead(ar); cState.Message.Append(Encoding.UTF8.GetChars(cState.Buffer, 0, bytes)); if (bytes != 0) { authStream.BeginRead(cState.Buffer, 0, cState.Buffer.Length, new AsyncCallback(EndReadCallback), cState); return; } } catch (Exception e) { // A real application should do something // useful here, such as logging the failure. Console.WriteLine("Client message exception:"); Console.WriteLine(e); cState.Waiter.Set(); return; } IIdentity id = authStream.RemoteIdentity; Console.WriteLine("{0} says {1}", id.Name, cState.Message.ToString()); cState.Waiter.Set(); } } // ClientState is the AsyncState object. internal class ClientState { private AuthenticatedStream authStream = null; private TcpClient client = null; byte[] buffer = new byte[2048]; StringBuilder message = null; ManualResetEvent waiter = new ManualResetEvent(false); internal ClientState(AuthenticatedStream a, TcpClient theClient) { authStream = a; client = theClient; } internal TcpClient Client { get { return client;} } internal AuthenticatedStream AuthenticatedStream { get { return authStream;} } internal byte[] Buffer { get { return buffer;} } internal StringBuilder Message { get { if (message == null) message = new StringBuilder(); return message; } } internal ManualResetEvent Waiter { get { return waiter; } } } }
![継承階層](http://weblio.hs.llnwd.net/e7/img/dict/msdnc/minus.gif)
System.MarshalByRefObject
System.IO.Stream
System.Net.Security.AuthenticatedStream
System.Net.Security.NegotiateStream
![スレッド セーフ](http://weblio.hs.llnwd.net/e7/img/dict/msdnc/minus.gif)
![プラットフォーム](http://weblio.hs.llnwd.net/e7/img/dict/msdnc/minus.gif)
Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。
![バージョン情報](http://weblio.hs.llnwd.net/e7/img/dict/msdnc/minus.gif)
![参照](http://weblio.hs.llnwd.net/e7/img/dict/msdnc/minus.gif)
- NegotiateStream クラスのページへのリンク