Поделиться через


Безопасность транспорта с анонимным клиентом

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

Пример приложения см. в разделе Безопасность транспорта WS. Дополнительные сведения безопасности транспорта см. в разделе Общие сведения о безопасности транспорта.

Дополнительные сведения б использовании сертификата со службой см. в разделах Работа с сертификатами и Как настраивать порт с использованием SSL-сертификата.

Использование безопасности передачи с анонимным клиентом

Характеристика Описание

Режим безопасности

Транспорт

Взаимодействие

С существующими веб-службами и клиентами

Проверка подлинности (сервера)

Проверка подлинности (клиента)

Да

На уровне приложения (без поддержки WCF)

Целостность

Да

Конфиденциальность

Да

Транспорт

HTTPS

Привязка

WsHttpBinding

Служба

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

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

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

Код

В следующем коде показано создание конечной точки с использованием безопасности транспорта:

' Create the binding.
Dim binding As New WSHttpBinding()
binding.Security.Mode = SecurityMode.Transport
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None

' Create the URI for the endpoint.
Dim httpUri As New Uri("https://localhost/Calculator")

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

' Open the service host.
myServiceHost.Open()
Console.WriteLine("Press Enter to exit....")
Console.ReadLine()

' Close the service.
myServiceHost.Close()
// Create the binding.
WSHttpBinding binding = new WSHttpBinding();
binding.Security.Mode = SecurityMode.Transport;
binding.Security.Transport.ClientCredentialType =
      HttpClientCredentialType.None;

// Create the URI for the endpoint.
Uri httpUri = new Uri("https://localhost/Calculator");

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

// Open the service host.
myServiceHost.Open();
Console.WriteLine("Press Enter to exit....");
Console.ReadLine();

// Close the service.
myServiceHost.Close();

Конфигурация

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

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="ServiceModel.Calculator">
        <endpoint address="https://localhost/Calculator" 
                  binding="wsHttpBinding"
                  bindingConfiguration="WSHttpBinding_ICalculator" 
                  name="SecuredByTransportEndpoint"
                  contract="ServiceModel.ICalculator" />
      </service>
    </services>
    <bindings>
      <wsHttpBinding>
        <binding name="WSHttpBinding_ICalculator">
          <security mode="Transport">
            <transport clientCredentialType="None" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <client />
  </system.serviceModel>
</configuration>

Клиент

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

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

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

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

Код

' Create the binding.
Dim myBinding As New WSHttpBinding()
myBinding.Security.Mode = SecurityMode.Transport
myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None

' Create the endpoint address. Note that the machine name 
' must match the subject or DNS field of the X.509 certificate
' used to authenticate the service. 
Dim ea As New EndpointAddress("https://machineName/Calculator")

' Create the client. The code for the calculator 
' client is not shown here. See the sample applications
' for examples of the calculator code.
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
// Create the binding.
WSHttpBinding myBinding = new WSHttpBinding();
myBinding.Security.Mode = SecurityMode.Transport;
myBinding.Security.Transport.ClientCredentialType =
    HttpClientCredentialType.None;

// Create the endpoint address. Note that the machine name 
// must match the subject or DNS field of the X.509 certificate
// used to authenticate the service. 
EndpointAddress ea = new
    EndpointAddress("https://machineName/Calculator");

// Create the client. The code for the calculator 
// client is not shown here. See the sample applications
// for examples of the calculator code.
CalculatorClient cc =
    new CalculatorClient(myBinding, ea);

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

    // Close the client.
    cc.Close();
}

Конфигурация

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

<configuration>
  <system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="WSHttpBinding_ICalculator" >
          <security mode="Transport">
            <transport clientCredentialType="None" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address="https://machineName/Calculator" 
                binding="wsHttpBinding"
                bindingConfiguration="WSHttpBinding_ICalculator" 
                contract="ICalculator"
                name="WSHttpBinding_ICalculator" />
    </client>
  </system.serviceModel>
</configuration>

См. также

Задачи

Безопасность транспорта WS

Основные понятия

Общие сведения о безопасности
Общие сведения о безопасности транспорта

Другие ресурсы

Модель безопасности для Windows Server App Fabric