How to specify Windows credentials in WCF client configuration file

Joe picture Joe · Jun 4, 2009 · Viewed 64.6k times · Source

I have a WCF service using BasicHttpBinding with Windows authentication. Most clients are domain accounts and connect to the service using their default credentials.

Now I want to connect to the service from an ASP.NET client that is running under a local account. I want to connect to the WCF service using windows credentials (domain\user and password) that are available to the ASP.NET application.

I know I can do this in code using ClientBase<T>.ClientCredentials.

Is there a way to specify the credentials (domain\user and password) in the client's web.config file so I don't have to change the code?

EDIT

If it can't be done in the configuration file, is there a way of using System.Net.ICredentials or System.Net.NetworkCredential as a credential for a WCF service?

The .NET Framework provides these as a homogenous way to provide network credentials, but with WCF this seems to have been thrown out in favour of a new incompatible system based on the unrelated System.ServiceModel.Description.ClientCredentials class.

EDIT 2

Accepting Marc's answer to the original question - it seems there is no way to do this in the client configuration file :(

I would see this as a deficiency in WCF - I don't accept that Microsoft should be deliberately discouraging us from putting credentials in the configuration file - after all they have to be stored somewhere, and the Framework includes facilities for encrypting the config file. I guess I could create a custom BehaviorExtensionElement for this, but it ought to be available out of the box.

It's also a bit inconsistent: the system.net/mailSettings/smtp/network configuration element allows credentials to be specified, so why not WCF?

Regarding the second question about using System.Net.NetworkCredential, it seems from this blog that it is possible, at least when using Windows authentication, with the following code:

factory.Credentials.Windows.ClientCredential =
   new System.Net.NetworkCredential(name, password, domain);

Answer

Steven picture Steven · Sep 17, 2010
Svc.ClientCredentials.UserName.UserName = AppSettings["WCFSvcUsername"];
Svc.ClientCredentials.UserName.Password = AppSettings["WCFSvcPassword"];

is incorrect. It is used with message security and clientCredentialType="UserName". You should use

Svc.ClientCredentials.Windows.ClientCredential = new NetworkCredential(...);