WCF – username password authentication

In asmx (old fashion web service) we could easily create client credentials in code. The authentication information is pushed to soap request’s header. The authentication code can be implemented as follows:

 TestService qs = new TestService ();
 AuthHeader credentials = new AuthHeader ();
 credentials.UserName   = "testUser";
 credentials.Password   = "pass";
 qs.AuthHeaderValue     = credentials; 

We need to write custom validator in WCF in order to validate client’s identity information. In custom validator class, validate method which gives username nad pass to us must be overrided.

// Username and password validator class

using System;
using System.Data;
using System.IdentityModel.Selectors;
using System.ServiceModel;

namespace BTS.Services.ValidationDemo
{
    public class CustomUserNamePasswordValidator : UserNamePasswordValidator
    {
        public override void Validate(string userName, string password)
        {
	       // The authentication logic here
	    }
    }
}

Service configuration

 <behaviors>
      <serviceBehaviors>
        <behavior name="BTS.Services.ValidationDemo.Behavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <serviceThrottling maxConcurrentCalls="483647"
            maxConcurrentInstances="483647"
            maxConcurrentSessions="483647"/>
          <serviceCredentials>
            <userNameAuthentication
        userNamePasswordValidationMode="Custom"
        customUserNamePasswordValidatorType="BTS.Services.ValidationDemo.CustomUserNamePasswordValidator, BTS.Services.ValidationDemo"/>
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
</behaviors>

Additionally, If we should get username and pass info outside of the validator class, they can be taken from security tokens as follows:

// To get username and password inside of service

UserNameSecurityToken securityToken = OperationContext.Current.IncomingMessageProperties.Security.IncomingSupportingTokens[0].SecurityToken as System.IdentityModel.Tokens.UserNameSecurityToken; 

string username = securityToken.UserName; 
string password = securityToken.Password;

Have good coding…

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s