How To Call WCF Web Service With Authentication Credentials

Posted by Ahmed Tarek Hasan on 2/01/2013 09:28:00 PM with No comments
When you deal with WCF web services, sometimes you need to call a web service with certain authentication credentials -username (with/without domain) and password- to be able to take some high privilege actions.

Me myself faced such case and tried to find the proper way to do it. So, I found that the reference I created to the web service has a property called "Credentials" through which I can provide my credentials.

But, when I tried my code, I found that my request is still not authenticated. After further investigations, I decided to search msdn for all properties related to the authentication topic to see if I am missing something.

So, I found that my reference class to my web service inherits from "System.Web.Services.Protocols.SoapHttpClientProtocol" class. So, by the aid of google, I found some interesting results. It is not enough to set the "Credentials" property of my reference. I have three more properties to set to achieve what I want, so lets see some code.

//Creating a reference to your WCF web service
MyCustomService service = new MyCustomService();

AllowAutoRedirect is "true" to automatically redirect the client to follow server redirects; otherwise, "false". The default is "false".

If you send authentication information, such as a user name and password,
you do not want to enable the server to redirect, because this can compromise security
service.AllowAutoRedirect = false;

PreAuthenticate is "true" to pre-authenticate the request; otherwise, "false". The default is "false".

When PreAuthenticate is false, a request is made to the Web service method
without initially attempting to authenticate the user. If the Web service allows anonymous
access, then the Web service method is executed, else, a 401 HTTP return code is sent back.
service.PreAuthenticate = true;

UseDefaultCredentials is "true" if the Credentials property is set to the value of the CredentialCache.DefaultCredentials property; otherwise, "false".
service.UseDefaultCredentials = false;

//Providing credentials
service.Credentials = new NetworkCredential("userName", "password", "domain");

That's it, after setting the four properties "AllowAutoRedirect", "PreAuthenticate", "UseDefaultCredentials" and "Credentials" properly I could get my call to my web service authenticated.