My web application uses Basic Authentication (SSL enabled). This application consumes
a web service which is under Basic Authentication as well. I am using Visual Stuio.net to develop.
Since I am using VS.Net, it is easy to start using the web service, you click on Add Web Refrerence,point it to the web service url (http://myserver/mywebservice/service.asmx). At this point VS.Net creates your proxy class in built with the mechanism to talk to your web service. You are all set,
You are ready to can access your web methods now!
Now only small challenge I faced here is around the authentication. When I initially called my web method, it threw me an HTTP Error 401:Authorization Required. Ofcourse, I was not passing any authentication credentials to the web serive (which BTW uses Basic Authentication).
So I changed my code to add these two lines,
proxy.PreAuthenticate = true;
proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
before the actual call is made. Still no luck, why? I overlooked the fact that passing DefaultCredentials works only for NTLM and Kerberos (Windows Authentication).
Now at this point, I want to stress the importance of PreAuthenticate Property.
It is important to set this to true when dealing with a secured web service.
According to Microsoft
The proxy's PreAuthenticate property can be set to true or false.
Set it to true to supply specific authentication credentials to cause a WWW-authenticate HTTP header to be passed with the Web request. This saves the Web server denying access on the request, and performing authentication on the subsequent retry request.
So I changed my code again,
MyWebService proxy = new MyWebService();
string pwd = HttpContext.Current.Request.ServerVariables["AUTH_PASSWORD"];
string uid = HttpContext.Current.Request.ServerVariables["AUTH_USER"];
NetworkCredential nc = new NetworkCredential(uid,pwd,"mydomain");
proxy.Credentials = nc;
proxy.PreAuthenticate = true;
and make the call !
With this change it all started working, I am getting the user id and password from my application that has already authenticated the user, create a credentical and pass it to the web service.
:)
0 comments:
Post a Comment