I was looking for a way to Start / Stop Windows Services residing in a remote machine using C# code, and found the following code sample. It works fine for me. It is coded using Impersonation Technique, which apparently requires both the machines (let's say A and B) have a user account with the same UserName + Password combination.
private bool impersonateValidUser(String userName, String machineName, String passWord)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUserA(userName, machineName, passWord,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if (token != IntPtr.Zero)
{
CloseHandle(token);
}
if (tokenDuplicate != IntPtr.Zero)
{
CloseHandle(tokenDuplicate);
}
return false;
}
The values of two LOGON32 variables are as follows:
int LOGON32_LOGON_INTERACTIVE = 2;
int LOGON32_PROVIDER_DEFAULT = 0;
Now I need to know the answers to the following questions, so would greatly appreciate if somebody could help me.
1. An explanation of the code in general.
2. Why is it necessary for both machines to have user accounts with identical username + passoword combination?
3. Why is it the privileges of the two user accounts (Admin or Non-Admin) is irrelevant?
Thank you in advance.