The typical WCF client application is often the required to supply the client's credentials. Following code snippet shows how to create the proxy instance with username-password credentials:
ChannelFactory<ITestService> factory = new
ChannelFactory< ITestService>( binding, endpointAddress);
factory.Credentials.UserName.UserName = "damirdobric"; factory.Credentials.UserName.Password = "*******";
. . . |
|
All this works fine as long you do simple things. Imagine now, there is a case which requires that your code
destroy the current instance of the channel factory (see example above) and automatically create the new one. This seems to be a very simple task. All you need is to keep the instance of binding, the endpoint address and credentials itself. Following example shows how this should be typically done:
ChannelFactory<ITestService> newFactory = new
ChannelFactory< ITestService>( binding, endpointAddress);
newFactory.Credentials = oldFactory;
. . . |
|
Unfortunately, this example has more problems than you could imagine. First problem is that the ClientCredentials property is read-only. So, there is no way to set it directly. Because of that the only way is to copy all required properties form old credentials to new one. From the architecture point of view this is not recommended, because you do not know really how to copy credentials.
Do not forget that credentials could also be some custom credentials.
Following code shows how this can be done for any kind of credentials supported by WCF:
ChannelFactory<ITestService> newFactory = new
ChannelFactory< ITestService>( binding, endpointAddress);
newFactory.Endpoint.Behaviors.Remove<ClientCredentials>();
newFactory.Endpoint.Behaviors.Add(factory.Credentials);
. . . |
To be honest, the ClientCredentials property has a design I personally do not like much. It is just a bunch of too many properties. By any more sophisticated customization you are never able to know what credentials the caller has set. This makes difficult any manipulation of credentials.
The good thing is that the ClientCredentials clas is WCF behavior class (implements IEndpointBehavior). This makes it possible to manipulate credentials by using of WCF behaviors as shown in the last example.
Posted
May 01 2007, 12:18 AM
by
Damir Dobric