views:

361

answers:

3

Hi,

I'm writing some code to utilise a 3rd party component, and I need to supply an object which implements ICredentials when I start to use it.

If I write the following...

var credential = new NetworkCredential("MyUsername", "MyPassword");

...and pass "credential", it's fine. But I would like to pass the credentials of the current user (it's a Windows service, so runs as a specified user).

I have tried both of the following, but neither appear to work (or return anything):

NetworkCredential credential = System.Net.CredentialCache.DefaultCredentials;
NetworkCredential credential = CredentialCache.DefaultNetworkCredentials;

Can anyone suggest how to acquire an approriate object, which represents the credentials of the username that the service is running under ?

Thanks, Ross

A: 

You need to do impersonation, for example:

    System.Security.Principal.WindowsImpersonationContext impersonationContext;
impersonationContext = 
    ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();

//Insert your code that runs under the security context of the authenticating user here.

impersonationContext.Undo();

http://support.microsoft.com/kb/306158

Or you can use web.config:

<identity impersonate="true" />
Alex
Thanks, but I'm running as a Windows service, not as an ASP web page. All the suggestions I have so far found are ASP related. I already tried impersonation, but it doesn't help/work (in this context).I'm amazed that there appears to be no way to acquire the credentials of the current user (who is logged in after all), and have instead to code some hacky method to store the user's username and password. Yuk !(thanks for you suggestion though)
Ross Watson
A: 

have you tried WindowsIdentity.GetCurrent()?

you could also look at this example... http://www.codeproject.com/KB/vb/Windows_Service.aspx

yamspog
"have you tried WindowsIdentity.GetCurrent ?"Yes, it doesn't appear to help - even if you pass the result into Impersonate.The example just appeared to be an interesting (?) way to get the current username.Thanks
Ross Watson
A: 

I have the same problem with a WCF client scenario, see this thread http://stackoverflow.com/questions/3166150/how-do-i-tell-a-wcf-client-proxy-class-to-use-windows-authentication-and-the-wind

Mahol25