2011-06-29 21 views
3

こんにちは、私はC#のSSLクライアント/サーバ通信をサーバとクライアント証明書を使って相互認証しています。私は、私はSSLクライアント/サーバ相互認証

AuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) 

メソッドを使用する必要があるだろうと仮定し、私はcorrentだ

TcpClient client = new TcpClient(machineName, port); 
//Create an SSL stream that will close the client's stream. 
    SslStream sslStream = new SslStream(
    client.GetStream(), 
    false, 
    new RemoteCertificateValidationCallback(ValidateServerCertificate), 
    null 
    ); 
try 
{ 
    // The server name must match the name on the server certificate. 
    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; 
} 

:のみ、クライアント側で、私はそのようSTHを使用するサーバー証明書を使用して、SSL通信を行うために管理?誰もが周りのすべてのものでそれを使用する方法を私に見せてもらえますか?サーバー側でも、基本的な例を教えてください?

ありがとうございました。

+0

あなたはWCFのフレームワークを使用するようにしようとしていない理由を私は求めることができますか?彼らは相互認証のオプションがあり、あなたのために多くの重労働をします。 [WCF documentation](http://msdn.microsoft.com/en-us/netframework/aa663324) – Jay

答えて

2
  1. あなたは、それをシンプルに作成pluralsight self cert
  2. は、新しいWebサイトを作成し、WCFサービスが選択image
  3. のように証明書を生成しダウンロードするには、X509の自己証明書が必要です。
  4. 新しいコンソールアプリケーションをソリューションに追加して、サービスをテストします。サービスのweb.configファイルで
  5. 設定入れる:サービス・クラスで

    <?xml version="1.0"?> 
    <configuration> 
    <system.serviceModel> 
    <behaviors> 
        <serviceBehaviors> 
         <behavior name="ServiceCredentialsBehavior"> 
          <serviceCredentials> 
           <serviceCertificate findValue="cn=cool" storeName="TrustedPeople" storeLocation="CurrentUser" /> 
          </serviceCredentials> 
          <serviceMetadata httpGetEnabled="true" /> 
         </behavior> 
        </serviceBehaviors> 
    </behaviors> 
    <services> 
        <service behaviorConfiguration="ServiceCredentialsBehavior" name="Service"> 
         <endpoint address="" binding="wsHttpBinding" bindingConfiguration="MessageAndUserName" name="SecuredByTransportEndpoint" contract="IService"/> 
        </service> 
    </services> 
    <bindings> 
        <wsHttpBinding> 
         <binding name="MessageAndUserName"> 
          <security mode="Message"> 
           <message clientCredentialType="UserName"/> 
          </security> 
         </binding> 
        </wsHttpBinding> 
    </bindings> 
    <client/> 
    

  6. 、既存のメソッドを削除して追加します。

    パブリック文字列TestAccessを() { OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name;を返します。 IServiceで }

  7. 、データ契約を削除する操作コントラクトを削除し、新しい操作契約を追加します。

    [OperationContract]
    パブリック文字列TestAccess();

  8. 実行サービスおよび当社のサービスにクライアントアプリケーションで

  9. クライアントの設定サービス参照を追加します。

    <?xml version="1.0" encoding="utf-8"?> 
    <configuration> 
        <system.serviceModel> 
        <behaviors> 
        <endpointBehaviors> 
         <behavior name="LocalCertValidation"> 
          <clientCredentials> 
           <serviceCertificate> 
            <authentication certificateValidationMode="PeerTrust" trustedStoreLocation="CurrentUser" /> 
           </serviceCertificate> 
          </clientCredentials> 
         </behavior> 
        </endpointBehaviors> 
    </behaviors> 
    <bindings> 
        <wsHttpBinding> 
         <binding name="WSHttpBinding_IService" > 
          <security mode="Message"> 
           <message clientCredentialType="UserName" /> 
          </security> 
         </binding> 
        </wsHttpBinding> 
    </bindings> 
    <client> 
        <endpoint address="your service addresss" 
           binding="wsHttpBinding" 
           bindingConfiguration="WSHttpBinding_IService" 
           contract="ServiceReference1.IService" 
           name="WSHttpBinding_IService" behaviorConfiguration="LocalCertValidation"> 
         <identity> 
          <dns value ="cool" /> 
         </identity> 
        </endpoint> 
    </client> 
    

  10. クライアントコード:

    ServiceClientクライアントを=新しいですServiceClient();
    client.ClientCredentials.UserName.UserName = "あなたのWindowsユーザー";
    client.ClientCredentials.UserName.Password = "あなたのWindowsユーザーのパスワード";
    Console.WriteLine(client.TestAccess());
    コンソール。読み込まれた行();
    よろしく、

    はSergiu:あなたがWindowsログイン/パスワードを使用したくない場合は

  11. カスタムユーザー/ passwdのバリデータ->msdnを作成する必要があります。
+4

質問はWCFについて言及していないので、この回答はすべてWCFに関するものです。 – deerchao

6
static void HTTPSClient() 
{ 
    try 
    { 
     string message = "GET/HTTP/1.0\r\nHost: host.com\r\n\r\n"; 

     byte[] data = System.Text.Encoding.ASCII.GetBytes(message); 

     string server = "host.com"; 
     int nPort = 443; 
     TcpClient client = new TcpClient(server, nPort); 

     X509Certificate2Collection cCollection = new X509Certificate2Collection(); 
     cCollection.Add(new X509Certificate2("cert.pfx", "password")); 


     using (SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null)) 
     { 
      // Add a client certificate to the ssl connection 
      sslStream.AuthenticateAsClient(server, cCollection, System.Security.Authentication.SslProtocols.Default, true); 

      sslStream.Write(data, 0, data.Length); 

      data = new Byte[8192]; 
      int bytes = 0; 
      string responseData = ""; 

      do 
      { 
       bytes = sslStream.Read(data, 0, data.Length); 
       if (bytes > 0) 
       { 
        responseData += System.Text.Encoding.ASCII.GetString(data, 0, bytes); 
       } 
      } 
      while (bytes > 0); 

      Console.WriteLine("Response: " + responseData); 
     } 

     // Disconnect and close the client 
     client.Close(); 
    } 
    catch (Exception ex) 
    { 
     Console.WriteLine("Error: " + ex.ToString()); 
    } 
} 

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; 
} 
+2

ようこそstackoverflowへ!ポストの精度を向上させるためのサンプルコードの簡単な説明を提供する方が良いでしょう。 –

関連する問題