Implement a UserNamePasswordValidator for WCF Service hosted in IIS


Recently I was working with a customer to implement a custom UserNamePasswordValidator for his WCF application. You can download a sample on this topic and others from Windows Communication Foundation (WCF) and Windows Workflow Foundation (WF) Samples for
.NET Framework 4
.

Although the WCF sample works perfectly you may run into problems transferring the solution to a WCF Service hosted in IIS when it comes time to configure the UserNamePasswordValidator in the serviceCredentials element. In the WCF samples, notice “server” after the type specified:

<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode=”Custom”
customUserNamePasswordValidatorType=”Microsoft.ServiceModel.Samples.CalculatorService.CustomUserNameValidator,
service” />
</serviceCredentials>

This “service” is actually a location to the name of the class. There may be a number of ways to accomplish this task but the method I choose seemed simple and straightforward enough. First, inside your WCF project hosted in IIS, create a new class file and allow that file to be placed in the
App_Code directory. If you do not have a namespace already defined, make sure to include one to wrap this class:

namespace mynamespace

{
    public class UserNameValidator : System.IdentityModel.Selectors.UserNamePasswordValidator
    {
        public override void Validate(string userName, string password)
        {
            //Control Logic here
        }
    }
}

By default there is no namespace defined in the WCF solution for IIS hosted services. So the step of adding a namespace becomes important when we have to declare the customUserNamePasswordValidatorType later in the web.config. If you drop out any part of the namespace, including
the class, you will receive some error which essentially states the runtime was unable to find the type.

          <serviceCredentials>
            <userNameAuthentication customUserNamePasswordValidatorType=”mynamespace.UserNameValidator, App_Code/UserNameValidator” userNamePasswordValidationMode=”Custom” />
          </serviceCredentials> 

Finally, the last point of interest comes after the Type is specified in customUserNamePasswordValidatorType. App_Code/UserNameValidator, is the location pointer to the class UserNameValidator so in your web solution this will be different than the console solution in the WCF samples.

Summary:

Wrap your password validator class in a namespace and remember to point to the App_Code directory when configuring a custom UserNamePasswordValidator for WCF.

Comments (1)

  1. Mauricio says:

    Hello Tony,
    I have the validator class and all is OK. But I want to know which user have logged in OperationContract. Do you have an option to know that?

Skip to main content