How to secure wcf service using username and password

Securing a WCF Service with username and password

Step I: Create a visual studio project with template wcf service application. The service will contain a method that returns server time to user if the user is authenticated. Following are the interfaces and the implementation of the interface.

public interface IServerTime
	string GetServerTime();

public class ServerTime : IServerTime
	public string GetServerTime()
		return DateTime.Now.ToString();

Step II: Create a class that extends from UserNamePasswordValidator class and override the validate method. The validate method contains the custom code to validate client based on username and password. Add reference to System.IdentityModel and System.IdentityModel.Selectors namespace

public class UserValidator : UserNamePasswordValidator
	public override void Validate(string userName, string password)
		if (userName == null || password == null)
			throw new ArgumentNullException();
		if (!(userName == "nikhil" && password == "nikhil"))
			throw new FaultException("Incorrect Username or Password");

Step II: Modify the web.config file

    <binding name="ws">
      <security mode="Message">
        <message clientCredentialType="UserName"/>

    <behavior name="myBehavior">
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="false"/>
        <serviceCertificate findValue="Test"
        <userNameAuthentication userNamePasswordValidationMode="Custom"
        customUserNamePasswordValidatorType="SecureService.ServerTime, SecureService"/>

  <service name="SecureService.ServerTime" behaviorConfiguration="myBehavior">
    <endpoint address="" binding="wsHttpBinding" contract="SecureService.IServerTime" bindingConfiguration="ws"></endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>

Step III: Deploy the service and create the client. Add service reference. Add reference to System.ServiceModel

ClientTime.ServerTimeClient client = new ClientTime.ServerTimeClient(); client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
client.ClientCredentials.UserName.UserName = "Nikhil";
client.ClientCredentials.UserName.Password = "Nikhil";
string time=client.GetServerTime();

One thought on “How to secure wcf service using username and password

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s