Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Adding Support for PasswordDigest to WCF Service References

0.00/5 (No votes)
24 Sep 2015CPOL 12.3K  
Adding support for PasswordDigest to WCF Service References

Introduction

I recently had an issue at work connecting to a service that required PasswordDigest authentication using WCF.

Background

MS used to support PasswordDigest authentication with WSE 3.0. But in the migration to WCF, this support was dropped (http://msdn.microsoft.com/en-us/library/aa738565.aspx). After searching for solutions, I encountered Akos' blog on MSDN with a custom UserName token that would add the correct tokens to the SOAP envelop (http://blogs.msdn.com/b/aszego/archive/2010/06/24/usernametoken-profile-vs-wcf.aspx).

The only problem that I ran into is the provided code used the ChannelFactory to instantiate the proxy client. I was using service references, so the ChannelFactory was encapsulated in the ClientBase<>. Plus, I had 17 service references that I had to modify.

So I created this generic factory wrapper for the service references to update the ClientCredentials in the ChannelFactory.

I have also provided a StructureMap registration statement to show how this factory could be used with DI.

Using the Code

C#
public class PasswordDigestChannelFactory<tporttypeclient, tplugin="">
    where TPortTypeClient : ClientBase<tplugin>, TPlugin, new()
    where TPlugin : class
{
    public PasswordDigestChannelFactory(string endpointConfigurationName)
    {
        _endpointConfigurationName = endpointConfigurationName;
    }

    private readonly string _endpointConfigurationName;

    public TPlugin GetClient()
    {
        var args = new[] {_endpointConfigurationName};
        var portInstance = Activator.CreateInstance(typeof 
		(TPortTypeClient), args) as ClientBase<tplugin>;
        
        // replace ClientCredentials with UsernameClientCredentials
        var username = "username";
        var password = "password";

        var credentials = new UsernameClientCredentials(new UsernameInfo(username, password));
        portInstance.ChannelFactory.Endpoint.Behaviors.Remove(typeof (ClientCredentials));
        portInstance.ChannelFactory.Endpoint.Behaviors.Add(credentials);
    
        return portInstance as TPlugin;
    }
}

//  StructureMap injection
For<porttype>()
    .Use((new PasswordDigestChannelFactory<porttypeclient, 
    porttype="">("endPoint")).GetClient());    

History

  • 0.1 - Original tip

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)