Compartir a través de


Seguridad de transporte con autenticación básica

La ilustración siguiente muestra un servicio Windows Communication Foundation (WCF) y cliente. El servidor necesita un certificado X.509 válido que se puede utilizar para Capa de sockets seguros (SSL) y los clientes deben confiar en el certificado del servidor. Además, el servicio Web ya tiene una implementación SSL que se puede usar. Para obtener más información sobre cómo habilitar la autenticación básica en Internet Information Services (IIS), consulte https://go.microsoft.com/fwlink/?LinkId=83822.

Seguridad de transporte con autenticación básica

Característica Descripción

Modo de seguridad

Transporte

Interoperabilidad

Con clientes de servicios Web existentes y servicios

Autenticación (servidor)

Autenticación (cliente)

Sí (utilizar HTTPS)

Sí (a través del nombre de usuario/Contraseña)

Integridad

Confidencialidad

Transport

HTTPS

Enlace

WSHttpBinding

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 un nombre de usuario del dominio de Windows y contraseña para la seguridad de la transferencia. Tenga en cuenta que el servicio exige un certificado X.509 que autentique al cliente. Para obtener más información, consulte Trabajar con certificados y Cómo: Configurar un puerto con un certificado SSL.

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

' 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.
myServiceHost.Open()
Console.WriteLine("Listening...")
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.Basic;

// 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.
myServiceHost.Open();
Console.WriteLine("Listening...");
Console.WriteLine("Press Enter to exit.");
Console.ReadLine();

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

Configuración

Lo siguiente configura un servicio para utilizar la autenticación básica con seguridad de nivel de transporte:

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

Cliente

Código

El código siguiente muestra el código de cliente que incluye el nombre de usuario y contraseña. Tenga en cuenta que el usuario debe proporcionar un nombre de usuario de Windows válido y contraseña. El código para devolver el nombre de usuario y la contraseña no se muestra aquí. Utilice un cuadro de diálogo u otra interfaz para solicitar la información al usuario.

ms733775.note(es-es,VS.100).gifNota:
El nombre de usuario y contraseña solo se pueden establecer utilizando el código.

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

' 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)

' The client must provide a user name and password. The code
' to return the user name and password is not shown here. Use
' a database to store the user name and passwords, or use the 
' ASP.NET Membership provider database.
cc.ClientCredentials.UserName.UserName = ReturnUsername()
cc.ClientCredentials.UserName.Password = ReturnPassword()

' 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.Basic;

// 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);
// The client must provide a user name and password. The code
// to return the user name and password is not shown here. Use
// a database to store the user name and passwords, or use the 
// ASP.NET Membership provider database.
cc.ClientCredentials.UserName.UserName = ReturnUsername();
cc.ClientCredentials.UserName.Password = ReturnPassword();
try
{
    // Begin using the client.
    cc.Open();
    Console.WriteLine(cc.Add(100, 11));
    Console.ReadLine();

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

Configuración

El código siguiente muestra la configuración del cliente.

ms733775.note(es-es,VS.100).gifNota:
No puede utilizar la configuración para establecer el nombre de usuario y contraseña. La configuración mostrada aquí se debe aumentar utilizando el código para establecer el nombre de usuario y contraseña.

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

Vea también

Tareas

Cómo: Configurar un puerto con un certificado SSL

Referencia

ClientCredentials
UserNamePasswordClientCredential

Conceptos

Trabajar con certificados
Información general sobre seguridad

Otros recursos

ClientCredentials
Modelo de seguridad para Windows Server App Fabric