[英]SSL client/server mutual authentication
您好,我正在嘗試在 C# 中進行 ssl 客戶端/服務器通信,並使用服務器和客戶端證書進行相互身份驗證。 A 設法僅使用服務器證書進行 ssl 通信,在客戶端我使用這樣的東西:
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;
}
我想我需要使用
AuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
方法,我對嗎? 誰能告訴我如何將它與周圍的所有東西一起使用?即使在服務器端,或者指向一個基本示例?
十分感謝。
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;
}
在 web.config 的 service put 配置中:
<?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/>
在服務 class 中,刪除現有方法並添加:
公共字符串 TestAccess() { return OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name; }
在 IService 中刪除數據合約,刪除操作合約並添加新的操作合約:
[運營合同]
公共字符串 TestAccess();
運行服務並將客戶端應用程序中的服務引用添加到我們的服務
客戶端配置:
<?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>
客戶端代碼:
服務客戶端客戶端 = 新服務客戶端();
client.ClientCredentials.UserName.UserName = "您的 windows 用戶";
client.ClientCredentials.UserName.Password = "您的 windows 用戶密碼";
Console.WriteLine(client.TestAccess());
Console.ReadLine();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.