Authentication

patterns & practices Developer Center

  • How to: Authenticate Users Against the SQL Server Membership Provider
  • How to: Authenticate Users Against Active Directory
  • How to: Authenticate Users Against Active Directory Without Windows Authentication
  • How to: Authenticate Users with Certificates
  • How to: Map Certificates with Windows Accounts
  • How to: Authenticate Users Against a Custom User Store

How to: Authenticate Users Against the SQL Server Membership Provider

If your user information is already stored in a Microsoft SQL Server Membership database, or if you are building an Internet-facing WCF application from scratch, you can use the SQL Server membership provider to authenticate your WCF service clients. The SQL Server membership provider authenticates all incoming client credentials against the credentials stored in the SQL Server Membership database. The membership feature is a good choice because it allows you to enable username authentication without writing and maintaining custom code.

Perform the following steps to configure the SQL Server membership provider to work with username authentication in your WCF application:

  1. Configure your SQL Server database for membership. From a Visual Studio 2008 command prompt, run the following command:

    aspnet_regsql -S .\SQLExpress -E -A m -d <<YourDatabaseName>>
    

    In this command:

    • -S specifies the server, which is (.\SQLExpress) in this example.
    • -E specifies to use Windows authentication to connect to SQL Server.
    • -A m specifies to add only the membership feature. For simple authentication against a SQL Server user store, only the membership feature is required.
    • -d specifies the SQL Server database name. If this option is not used, a default aspnetdb database will be created.
    • For a complete list of the commands, run Aspnet_regsql /?
  2. Modify your web.config file in your WCF service application by adding the following sections:

    <connectionStrings>
      <add name="MyLocalSQLServer"
           connectionString="Initial Catalog=<<YourDatabaseName>>;
          data source=.\sqlexpress;Integrated Security=SSPI;" />
    </connectionStrings>
    
    …
    <system.web>
      ...
      <membership defaultProvider="MySqlMembershipProvider" >
        <providers>
          <clear/>
          <add name="MySqlMembershipProvider"
               connectionStringName="MyLocalSQLServer"
               applicationName="MyAppName"
               type="System.Web.Security.SqlMembershipProvider" />
        </providers>
      </membership>
    </system.web>
    …
    
  3. Configure the service to use username authentication:

    …
    <bindings>
      <wsHttpBinding>
        <binding name="wsHttpEndpointBinding">
          <security>
            <message clientCredentialType="UserName" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    
  4. Configure the service to use the SQL Server membership provider:

    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
    
          <serviceCredentials>
            <userNameAuthentication userNamePasswordValidationMode="MembershipProvider"
              membershipProviderName="MySqlMembershipProvider" />
          </serviceCredentials>
    
        </behavior>
      </serviceBehaviors>
    </behaviors>
    …
    

Additional Resources

How to: Authenticate Users Against Active Directory

Use Windows authentication when both the client and service are in trusted domains, or when users are stored in local machine accounts, such as in an intranet scenario. By using Windows authentication with the Microsoft Active Directory directory service, you benefit from a unified identity store, centralized account administration, enforceable account and password policies, and strong authentication that avoids sending passwords over the network.

If Windows authentication is not possible because of infrastructure limitations such as a firewall between clients and Active Directory, consider using username authentication instead. If you are using username authentication, the username/password for the user will be automatically mapped to a Windows account.

The following example shows how to configure the client credentials in WCF to use Windows authentication:

…
<bindings>
  <wsHttpBinding>
    <binding name="wsHttpEndpointBinding">
      <security>
        <message clientCredentialType="Windows" />
      </security>
    </binding>
  </wsHttpBinding>
</bindings>
…

Additional Resources

How to: Authenticate Users Against Active Directory Without Windows Authentication

Use username authentication to authenticate users against Active Directory or local machine accounts, when you cannot use Windows authentication. By default, username authentication will map your user's credentials to Windows accounts and authenticate the users against Active Directory.

The following code snippet configures a WCF service to use username authentication:

…
<bindings>
  <wsHttpBinding>
    <binding name="wsHttpEndpointBinding">
      <security>
        <message clientCredentialType="UserName" />
      </security>
    </binding>
  </wsHttpBinding>
</bindings>
…

Note

Use message security to protect user credentials passed over the network.

Additional Resources

How to: Authenticate Users with Certificates

Client certificates can authenticate a client service account or multiple users to a WCF service. If you use a client certificate for each user, you can map each certificate to a Windows account.

Perform the following steps to authenticate users by using a client-side certificate:

  1. Install the service certificate on the WCF service machine:

    • If you are using message security, configure service credentials to set the name and location of the service certificate.
    • If you are using transport security with wsHttpBinding, install the service certificate on Internet Information Services (IIS) and configure the virtual directory to require Secure Sockets Layer (SSL) and client certificates.
  2. Configure the service to use certificates for the client credentials type, as shown in the following example:

          <wsHttpBinding>
            <binding name="WSHttpBinding_ICalculator">
              <security mode="Message">
                <message clientCredentialType="Certificate" />
              </security>
            </binding>
          </wsHttpBinding>
    
  3. Install the service certificate on the client machine.

  4. Configure the endpoint behavior to set the name and location of the client certificate.

Note

Make sure that the root CA certificate is in the Trusted Root Certification Authorities location on both the server and client machines.

Additional Resources

How to: Map Certificates with Windows Accounts

Client certificates are not mapped to Windows accounts by default. To do so, you set the mapClientCertificateToWindowsAccount property to true.

Perform the following steps to map certificates to Windows accounts:

  1. Decide between the IIS certificate mapping versus Active Directory certificate mapping.

    • IIS certificate mapping is useful if you need only a limited number of mappings, or a different mapping on each WCF service.
    • Use Active Directory certificate mapping when the account mappings are identical on all IIS servers. Active Directory mapping is easier to maintain than IIS mapping because you only have to create the mapping in one location.
  2. Configure IIS / Active Directory for mapping the certificates.

  3. After you have enabled the client certificate mapping feature, set the mapClientCertificateToWindowsAccount property to true as follows:

    <serviceBehaviors>
      <behavior name="MyServiceBehaviorForWebHttp">
    
         <serviceCredentials>
          <clientCertificate>
           <authentication mapClientCertificateToWindowsAccount="true" />
          </clientCertificate>
         </serviceCredentials>
    
      </behavior>
    </serviceBehaviors>
    

Additional Resources

How to: Authenticate Users Against a Custom User Store

To authenticate users against a custom user store, configure your application to use username authentication with a custom username and password validator. Configure the custom validator in a service behavior and implement it in a class library. Your service uses the username and password validator to authenticate your users based on your custom user store.

Configuring a custom validator for your WCF service

The following configuration snippet shows how to configure a custom validator for your WCF service:

  <system.serviceModel>
   ...
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          ...
          <serviceCredentials>
            <serviceCertificate findValue=" CN=FabrikamEnterprises " />
            <userNameAuthentication userNamePasswordValidationMode="Custom"
                        customUserNamePasswordValidatorType=
                               "MyUserNamePasswordValidator,Host" />
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

Implementing a custom username and password validator

The following code snippet shows how to implement a custom username and password validator:

using System;
using System.Collections.Generic;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Text;

namespace DerivativesCalculator
{
 public class MyUserNamePasswordValidator : UserNamePasswordValidator
 {
    public override void Validate(string userName, string password)
    {
      Console.Write("\nValidating username, {0}, and password, {1} ... ", userName, password);
       if ((string.Compare(userName, "don", true) != 0) || 
          (string.Compare(password, "hall", false) != 0))
          {
           throw new SecurityTokenException("Unknown user.");
          }
       Console.Write("Done: Credentials accepted. \n");
     }
  }
}

Additional Resources