En la ilustración siguiente, se muestran un servicio y un cliente de Windows Communication Foundation (WCF). 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 Autenticación básica.
Característica
Descripción
Modo de seguridad
Transporte
Interoperabilidad
Con clientes de servicios Web existentes y servicios
El código y la configuración siguientes están diseñados para ejecutarse de forma independiente. Realice una de las siguientes acciones:
Cree un servicio independiente mediante el código sin configuración.
Cree un servicio mediante la configuración proporcionada, pero sin definir ningún punto de conexión.
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 Procedimientos: Configurar un puerto con un certificado SSL.
C#
// 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();
' 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()
Configuración
Lo siguiente configura un servicio para utilizar la autenticación básica con seguridad de nivel de transporte:
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.
Nota
El nombre de usuario y contraseña solo se pueden establecer utilizando el código.
C#
// 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();
}
' 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
Configuración
El código siguiente muestra la configuración del cliente.
Nota
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.
Únase a la serie de reuniones para crear soluciones de inteligencia artificial escalables basadas en casos de uso reales con compañeros desarrolladores y expertos.
Obtenga información sobre cómo habilitar un servicio WCF para autenticar un cliente mediante un nombre de usuario y una contraseña de dominio de Windows, con código de ejemplo.
Obtenga información sobre cómo el servicio WCF especifica la autenticación de un cliente en ese servicio. En este ejemplo se especifica un certificado X.509 y un modo de transporte.
Revise este escenario, que muestra un cliente o servicio WCF que protege la seguridad de Windows. En este ejemplo, un servicio de intranet muestra información de recursos humanos.
Obtenga información sobre cómo habilitar la seguridad de transporte en un servicio WCF que reside en un dominio de Windows y al que llaman los clientes del mismo dominio.
Revise este escenario de WCF, que usa la seguridad de transporte para autenticar un servidor mediante un certificado en el que confía el cliente. El cliente no está autenticado.
Obtenga información sobre cómo establecer los tres modos de seguridad WCF comunes en la mayoría de los enlaces predefinidos: Transport, Message y TransportWithMessageCredential.