How to: Authenticate with a User Name and Password

This topic demonstrates how to enable a Windows Communication Foundation (WCF) service to authenticate a client with a user name and password, thereby granting access to a Windows domain.

In this scenario, the client is authenticated using the client's domain user name and password. To do this in code, use an instance of the WsHttpBinding class and set the security mode to Message. To do this in configuration, create a binding using the wsHttpBinding Element. This instructs WCF to use SOAP messages to transfer the data.

The client, on the other hand, must obtain a user name and password from the application user. On a Windows Form application, use a logon dialog box to ask for this information and store it in a SecureString object. Once the two values are known, set the UserName property and the Password property of the UserNamePasswordClientCredential class to configure the client credential.

To configure a service to authenticate with a user name and password in code

  1. Create an instance of the WSHttpBinding class.

  2. Set the Mode property of the WSHttpSecurity class to Message. The WSHttpSecurity object is accessible through the Security property of the WSHttpBinding class.

  3. Set the ClientCredentialType property of the MessageSecurityOverHttp class to UserName. The MessageSecurityOverHttp is accessed through the Message property of the WSHttpSecurity class, as shown in the following code.

    Dim myBinding As New WSHttpBinding()
    myBinding.Security.Mode = SecurityMode.Message
    myBinding.Security.Message.ClientCredentialType = _
        MessageCredentialType.UserName
    
    WSHttpBinding myBinding = new WSHttpBinding();
    myBinding.Security.Mode = SecurityMode.Message;
    myBinding.Security.Message.ClientCredentialType = 
        MessageCredentialType.UserName;
    

To configure a service to authenticate with a user name and password in configuration

  1. Add a wsHttpBinding Element to the <bindings> section of the Web.config file.

  2. Add a binding element to the wsHttpBinding element and set the configurationName attribute to a value appropriate to your needs.

  3. Add a <security> for <wsHttpBinding> element to the binding and set the mode attribute to "Message".

  4. Add a <message> for <security> for <wsHttpBinding> to the security binding, and set the clientCredentialType attribute to "UserName", as shown in the following code:

    <system.serviceModel> 
    <bindings>
       <wsHttpBinding>
          <binding name="Binding1">
             <security mode="Message">
                <message clientCredentialType="UserName"/>
          </security>
       </binding>
       </wsHttpBinding>
    </bindings>
    </system.serviceModel>
    
  5. Create a service that uses the new binding, as shown in the following code.

    <services>
       <service   
          type="Microsoft.ServiceModel.Samples.CalculatorService"
       behaviorConfiguration="CalculatorServiceBehavior">
             <!-- Use the base address provided by the host. -->
          <endpoint address=""
    binding="wsHttpBinding"
             bindingConfiguration="Binding1"
             contract="Microsoft.ServiceModel.Samples.ICalculator" />
       </service>
    </services>
    

Client Code

To get the user name and password from the user in code

  1. To get the user name and password from the user, you must use a user interface. The following code uses a command prompt to query the user for a user name and password. The user's input is replaced with an asterisk.

    Public Shared Function Returnpassword() As String 
        Console.WriteLine( _
        "Provide a valid machine or domain account. [domain\user]")
        Console.WriteLine("   Enter username:")
        Dim username As String = Console.ReadLine()
        Console.WriteLine("   Enter password:")
        Dim password As String = ""
        Dim info As ConsoleKeyInfo = Console.ReadKey(True)
        While info.Key <> ConsoleKey.Enter
            If info.Key <> ConsoleKey.Backspace Then
                password += info.KeyChar
                info = Console.ReadKey(True)
            ElseIf info.Key = ConsoleKey.Backspace Then
                If Not String.IsNullOrEmpty(password) Then
                    password = password.Substring(0, _
                       password.Length - 1)
                End If
                info = Console.ReadKey(True)
            End If
        End While
        Dim i As Integer
        For i = 0 To password.Length
            Console.Write("*")
        Next i
        Return password
    
    End Function
    
    public static string Returnpassword()
    {
        Console.WriteLine("Provide a valid machine or domain account. [domain\\user]");
        Console.WriteLine("   Enter username:");
        string username = Console.ReadLine();
        Console.WriteLine("   Enter password:");
        string password = "";
        ConsoleKeyInfo info = Console.ReadKey(true);
        while (info.Key != ConsoleKey.Enter)
        {
            if (info.Key != ConsoleKey.Backspace)
            {
                password += info.KeyChar;
                info = Console.ReadKey(true);
            }
            else if (info.Key == ConsoleKey.Backspace)
            {
                if (!string.IsNullOrEmpty(password))
                {
                    password = password.Substring
                    (0, password.Length - 1);
                }
                info = Console.ReadKey(true);
           }
        }
        for (int i = 0; i < password.Length; i++)
        Console.Write("*");
    return password;
        }
    
  2. Create an instance of the client class as shown in the following code.

    Dim client As New CalculatorClient("default")
    
    CalculatorClient client = new CalculatorClient("default");
    
  3. Set the Password property of the UserNamePasswordClientCredential class to the password. The class is accessible from the client object, as shown in the following code.

    client.ClientCredentials.UserName.Password = ReturnPassword()
    
    client.ClientCredentials.UserName.Password = ReturnPassword();
    
  4. Set the UserName property to the user's user name.

    client.ClientCredentials.UserName.UserName = ReturnUsername()
    
    client.ClientCredentials.UserName.UserName = ReturnUsername();
    
  5. Call the methods of the service.

    Dim value1 As Double = client.Add(100, 15.99)
    
    double value1 = client.Add(100, 15.99);
    
  6. When done, call the Close method of the client.

    client.Close()
    
    client.Close();
    

See Also

Reference

WsHttpBinding
WSHttpSecurity
SecurityMode
UserName
Password
UserNamePasswordClientCredential
Mode
ClientCredentialType

Concepts

Transport Security with Basic Authentication
Distributed Application Security

Other Resources

wsHttpBinding Element


© 2007 Microsoft Corporation. All rights reserved.
Build Date: 2009-08-07