Безопасность сообщений с клиентом Windows

В этом сценарии показан клиент и сервер Windows Communication Foundation (WCF), защищенные режимом безопасности сообщений. Клиент и служба проходят проверку подлинности с использованием учетных данных Windows.

Message security with a Windows client

Characteristic Description
Режим безопасности Сообщение
Совместимость Только WCF
Проверка подлинности (сервера) Взаимная проверка подлинности сервера и клиента
Проверка подлинности (клиента) Взаимная проверка подлинности сервера и клиента
Целостность Да, используется общий контекст безопасности
Конфиденциальность Да, используется общий контекст безопасности
Транспорт NET.TCP
Привязка NetTcpBinding

Service

Предполагается, что представленные ниже код и конфигурация выполняются независимо. Выполните одно из следующих действий:

  • Создайте автономную службу, используя код без конфигурации.

  • Создайте службу, используя предоставленную конфигурацию, но не определяйте конечные точки.

Код

В следующем коде показано создание конечной точки службы, которая использует безопасность сообщений для установления защищенного контекста с компьютером Windows.

// Create the binding.
NetTcpBinding binding = new NetTcpBinding();
binding.Security.Mode = SecurityMode.Message;
binding.Security.Message.ClientCredentialType =
    MessageCredentialType.Windows;

// Create the URI for the endpoint.
Uri netTcpUri = new Uri("net.tcp://localhost:8008/Calculator");

// Crate the service host and add an endpoint.
ServiceHost myServiceHost = new ServiceHost
    (typeof(Calculator), netTcpUri);
myServiceHost.AddServiceEndpoint(
    typeof(ICalculator), binding, "");

// Open the service.
myServiceHost.Open();
Console.WriteLine("Listening ....");
Console.ReadLine();

// Close the service.
myServiceHost.Close();
' Create the binding.
Dim binding As New NetTcpBinding()
binding.Security.Mode = SecurityMode.Message
binding.Security.Message.ClientCredentialType = MessageCredentialType.Windows

' Create the URI for the endpoint.
Dim netTcpUri As New Uri("net.tcp://localhost:8008/Calculator")

' Crate the service host and add an endpoint.
Dim myServiceHost As New ServiceHost(GetType(ServiceModel.Calculator), netTcpUri)
myServiceHost.AddServiceEndpoint(GetType(ICalculator), binding, "")

' Open the service.
myServiceHost.Open()
Console.WriteLine("Listening ....")
Console.ReadLine()

' Close the service.
myServiceHost.Close()

Настройка

Вместо кода для настройки службы можно использовать следующую конфигурацию:

<?xml version="1.0" encoding="utf-8"?>  
<configuration>  
  <system.serviceModel>  
    <services>  
      <service behaviorConfiguration=""  
               name="ServiceModel.Calculator">  
        <endpoint address="net.tcp://localhost:8008/Calculator"  
                  binding="netTcpBinding"  
                  bindingConfiguration="Windows"  
                  name="WindowsOverMessage"  
                  contract="ServiceModel.ICalculator" />  
      </service>  
    </services>  
    <bindings>  
      <netTcpBinding>  
        <binding name="Windows">  
          <security mode="Message">  
            <message clientCredentialType="Windows" />  
          </security>  
        </binding>  
      </netTcpBinding>  
    </bindings>  
    <client />  
  </system.serviceModel>  
</configuration>  

Клиент

Предполагается, что представленные ниже код и конфигурация выполняются независимо. Выполните одно из следующих действий:

  • Создайте автономный клиент, используя код (и код клиента).

  • Создайте клиент, который не определяет никаких адресов конечных точек. Вместо этого используйте конструктор клиента, который принимает в качестве аргумента имя конфигурации. Например:

    CalculatorClient cc = new CalculatorClient("EndpointConfigurationName");
    
    Dim cc As New CalculatorClient("EndpointConfigurationName")
    

Код

Следующий код служит для создания клиента. Привязка осуществляется к безопасности режима сообщений, и типу учетных данных клиента присваивается значение Windows.

// Create the binding.
NetTcpBinding myBinding = new NetTcpBinding();
myBinding.Security.Mode = SecurityMode.Message;
myBinding.Security.Message.ClientCredentialType =
    MessageCredentialType.Windows;

// Create the endpoint address.
EndpointAddress ea = new
    EndpointAddress("net.tcp://machineName:8008/Calculator");

// Create the client.
CalculatorClient cc =
    new CalculatorClient(myBinding, ea);

// Begin using the client.
try
{
    cc.Open();
    Console.WriteLine(cc.Add(200, 1111));
    Console.ReadLine();

    // Close the client.
    cc.Close();
}
' Create the binding.
Dim myBinding As New NetTcpBinding()
myBinding.Security.Mode = SecurityMode.Message
myBinding.Security.Message.ClientCredentialType = MessageCredentialType.Windows

' Create the endpoint address.
Dim ea As New EndpointAddress("net.tcp://machineName:8008/Calculator")

' Create the client.
Dim cc As New CalculatorClient(myBinding, ea)

' Begin using the client.
Try
    cc.Open()

    Console.WriteLine(cc.Add(100, 11))
    Console.ReadLine()

    ' Close the client.
    cc.Close()
Catch tex As TimeoutException
    Console.WriteLine(tex.Message)
    cc.Abort()
Catch cex As CommunicationException
    Console.WriteLine(cex.Message)
    cc.Abort()
Finally
    Console.WriteLine("Closed the client")
    Console.ReadLine()
End Try

Настройка

Следующая конфигурация используется для задания свойств клиента.

<?xml version="1.0" encoding="utf-8"?>  
<configuration>  
  <system.serviceModel>  
    <bindings>  
      <netTcpBinding>  
        <binding name="NetTcpBinding_ICalculator" >  
         <security mode="Message">  
            <message clientCredentialType="Windows" />  
          </security>  
        </binding>  
      </netTcpBinding>  
    </bindings>  
    <client>  
      <endpoint address="net.tcp://machineName:8008/Calculator"
                binding="netTcpBinding"  
                bindingConfiguration="NetTcpBinding_ICalculator"  
                contract="ICalculator"  
                name="NetTcpBinding_ICalculator">
      </endpoint>  
    </client>  
  </system.serviceModel>  
</configuration>  

См. также