Use Windows Service "Log on as" user as NetworkCredentials for a web request

983 Views Asked by At

I developped a windows service that is running Logged On as: a specific windows user. I use this user, because it has permission for web site I need to request in this windows service.

The issue is that when requesting the web, using CredentialsCache.DefaultNetworkCredentials i uses the credentials of the current user logged in(WindowsIdentity.GetCurrent()) to windows which has no access to this web. I

I need in some way to pass the Credentials of the Windows service's "Log In as" user:

WebRequest request = WebRequest.Create("some url");
// the user running the service can be get from here:
// WindowsIdentity.GetCurrent(), but not the password
request.Credentials = "some code tobtain the user from the service user"

If I use:

request.Credentials = CredentialCache.DefaultNetworkCredentials;

it uses the user from the windows account NOT the windows service account.

Any ideas?

1

There are 1 best solutions below

0
On

the user running the service can be get from here: WindowsIdentity.GetCurrent(), but not the password

If you can get the current WindowsIdentity, you should be able to impersonate it:

WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
using (WindowsImpersonationContext impersonatedUser = currentIdentity.Impersonate())
{
    // Check the identity.
    Console.WriteLine("After impersonation: " + WindowsIdentity.GetCurrent().Name);
    // Make the request
    WebRequest request = WebRequest.Create("https://google.com");
    // etc
}