NegotiateStream クラスとは? わかりやすく解説

NegotiateStream クラス

メモ : このクラスは、.NET Framework version 2.0新しく追加されたものです。

クライアント サーバー通信Negotiate セキュリティ プロトコル使用してクライアント認証と、オプションサーバー認証を行うストリーム提供します

名前空間: System.Net.Security
アセンブリ: System (system.dll 内)
構文構文

Public Class NegotiateStream
    Inherits AuthenticatedStream
Dim instance As NegotiateStream
public class NegotiateStream : AuthenticatedStream
public ref class NegotiateStream : public
 AuthenticatedStream
public class NegotiateStream extends AuthenticatedStream
public class NegotiateStream extends
 AuthenticatedStream
解説解説

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閉じたときに基になるストリーム閉じかどうか指定するオプションあります

使用例使用例

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;
             }
        }
    }
}
継承階層継承階層
System.Object
   System.MarshalByRefObject
     System.IO.Stream
       System.Net.Security.AuthenticatedStream
        System.Net.Security.NegotiateStream
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
NegotiateStream メンバ
System.Net.Security 名前空間



英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「NegotiateStream クラス」の関連用語

NegotiateStream クラスのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



NegotiateStream クラスのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2024 Microsoft.All rights reserved.

©2024 GRAS Group, Inc.RSS