dave823
dave823

Reputation: 1211

Calling ASMX Service from C# app with Windows authentication?

I have created simple .NET Web Service (ASMX) that I call from my .NET web application. The service and web app both use Windows Authetication.

com.mydomain.MyWebService webSrvc = new com.mydomain.MyWebService();
string output = webSrvc.MyServiceMethod();

I am now creating Windows app with C#, and would like to call the same web service from there. I have added a web reference in my project to the service, and I can make calls to the service web methods without issue. The problem is, inside the web methods, I am trying to retrieve the user's windows user name.

string username = User.Identity.Name; //always blank

This works when I call the web service from my web app, but when I call it from my windows app, it always returns blank, and User.Identity.IsAuthenticated is always false, if that is relevant. What am I missing here. I just need to get the Windows user username that is running the console app, that called the web service. I have tried setting the credentials of webSrvc to the ClientCache default credentials, but that doesn't solve the problem.

UPDATE: I don't know if this is useful, but I learned that if I use Environment.UserName, it will give "NETWORK_SERVICE", and then if i enable impersonation, it will give "IUSR_[host_name]". It seems like i'm just missing something really simple. I just want to get the current windows user, who is running the windows app (which calls the web service).

Upvotes: 2

Views: 12498

Answers (2)

pego
pego

Reputation: 127

Set

UseDefaultCredentials = true; 

This will authenticate the the currentuser (or the account the current process is running)

Upvotes: 6

Richthofen
Richthofen

Reputation: 2086

Are you passing network credentials to your web service object before calling it? Something like:

NetworkCredential credentials = new
NetworkCredential(UserName,SecurelyStroredPassword,Domain);

// Add the NetworkCredential to the CredentialCache.
credentialCache.Add(new Uri(webSrvc.Url), 
                   "Basic", credentials);

Cribbed from: http://msdn.microsoft.com/en-us/library/bfazk0tb.aspx

Basically when the web service is called from the web app you already have all the cookie and session info sticking around. When you write a standalone application it won't have access to the cookies, form data, etc.

Upvotes: 2

Related Questions