Seguridad de mensajes con clientes anónimos

El escenario siguiente muestra un cliente y el servicio protegido por la seguridad del mensaje Windows Communication Foundation (WCF). Un objetivo del diseño es utilizar la seguridad del mensaje en lugar de la seguridad de transporte, para que en el futuro pueda admitir un modelo basado en notificaciones más completo. Para obtener más información sobre cómo utilizar notificaciones más completas para la autorización, consulte Administración de notificaciones y autorización con el modelo de identidad.

Para obtener una aplicación de ejemplo, consulte Seguridad de mensaje anónima.

Seguridad de mensajes con clientes anónimos

Característica Descripción

Modo de seguridad

Mensaje

Interoperabilidad

Solo WCF

Autenticación (servidor)

La negociación inicial requiere la autenticación del servidor, pero no la autenticación del cliente

Autenticación (cliente)

Ninguno

Integridad

Sí, mediante el contexto de seguridad compartido

Confidencialidad

Sí, mediante el contexto de seguridad compartido

Transporte

HTTP

Servicio

El código y la configuración siguientes están diseñados para ejecutarse de forma independiente. Siga uno de los procedimientos siguientes:

  • Cree un servicio independiente mediante el código sin configuración.

  • Cree un servicio con la configuración proporcionada, pero sin definir ningún extremo.

Código

El código siguiente muestra cómo crear un extremo de servicio que utiliza la seguridad del mensaje.

' Create the binding. 
Dim binding As New WSHttpBinding()
binding.Security.Mode = SecurityMode.Message
binding.Security.Message.ClientCredentialType = _
    MessageCredentialType.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, "")

' Specify a certificate to authenticate the service.
myServiceHost.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, _
StoreName.My, X509FindType.FindByThumbprint, "00000000000000000000000000000000")

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

' Close the service.
myServiceHost.Close()
// Create the binding. 
WSHttpBinding binding = new WSHttpBinding();
binding.Security.Mode = SecurityMode.Message;
binding.Security.Message.ClientCredentialType =
    MessageCredentialType.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, "");

// Specify a certificate to authenticate the service.
myServiceHost.Credentials.ServiceCertificate.SetCertificate(
    StoreLocation.LocalMachine,
    StoreName.My,
    X509FindType.FindByThumbprint,
    "00000000000000000000000000000000");

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

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

Configuración

En lugar del código, se puede utilizar la siguiente configuración. El elemento de comportamiento del servicio se utiliza para especificar un certificado utilizado para autenticar el servicio al cliente. El elemento de servicio debe especificar el comportamiento mediante el atributo behaviorConfiguration. El elemento de enlace especifica que el tipo de credencial de cliente es None, de modo que permite a los clientes anónimos utilizar el servicio.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceCredentialsBehavior">
          <serviceCredentials>
            <serviceCertificate findValue="contoso.com" 
                                storeLocation="LocalMachine"
                                storeName="My" />
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="ServiceCredentialsBehavior" 
               name="ServiceModel.Calculator">
        <endpoint address="https://localhost/Calculator" 
                  binding="wsHttpBinding"
                  bindingConfiguration="WSHttpBinding_ICalculator" 
                  name="CalculatorService"
                  contract="ServiceModel.ICalculator" />
      </service>
    </services>
    <bindings>
      <wsHttpBinding>
        <binding name="WSHttpBinding_ICalculator" >
          <security mode="Message">
            <message clientCredentialType="None" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <client />
  </system.serviceModel>
</configuration>

Cliente

El código y la configuración siguientes están diseñados para ejecutarse de manera independiente. Realice uno de los procedimientos siguientes:

  • Cree un cliente independiente mediante el código (y el código de cliente).

  • Cree un cliente que no defina direcciones de extremo. En su lugar, utilice el constructor de cliente que adopta el nombre de configuración como un argumento. Por ejemplo:

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

Código

En el ejemplo de código siguiente se crea una instancia de cliente. El enlace utiliza seguridad en modo de mensaje y el tipo de credencial de cliente está establecido como ninguno.

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

' Create the endpoint address. 
Dim ea As New EndpointAddress("https://localhost/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
// Create the binding.
WSHttpBinding myBinding = new WSHttpBinding();
myBinding.Security.Mode = SecurityMode.Message;
myBinding.Security.Message.ClientCredentialType =
    MessageCredentialType.None;

// Create the endpoint address. 
EndpointAddress ea = new
    EndpointAddress("https://localhost/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();
}

Configuración

El siguiente código configura el cliente.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="WSHttpBinding_ICalculator" >
          <security mode="Message">
            <message clientCredentialType="None" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://machineName/Calculator"
        binding="wsHttpBinding"
        bindingConfiguration="WSHttpBinding_ICalculator" 
        contract="ICalculator"
        name="WSHttpBinding_ICalculator">
        <identity>
          <dns value="contoso.com" />
        </identity>
      </endpoint>
    </client>
  </system.serviceModel>
</configuration>

Vea también

Tareas

Seguridad de mensaje anónima

Conceptos

Información general sobre seguridad
Seguridad distribuida de aplicaciones
Identidad del servicio y autenticación

Otros recursos

Modelo de seguridad para Windows Server App Fabric