I am trying to start/stop a windows service in the code from a web
application.The web application runs as IUSR_ComputerName, but this
account does not have enough access rights to star/stop the service.
How do I impersonate the local system account, so that I can stop/start the service?
Loading
Rajesh VellorePosted Jul 6, 2009, 9:03 AM
zirano lattPosted May 11, 2009, 3:01 AM
You can easily impersonate by calling Impersonator.Impersonate("domain","username","password"); method.
public class Impersonator
{
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
public static bool Impersonate(string domain, string userName, string password)
{
IntPtr tokenHandle = new IntPtr(0);
IntPtr dupeTokenHandle = new IntPtr(0);
bool returnValue
try
{
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
tokenHandle = IntPtr.Zero;
dupeTokenHandle = IntPtr.Zero;
// Call LogonUser to obtain a handle to an access token.
returnValue = LogonUser(userName, domain, password,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
ref tokenHandle);
}
catch (Exception ex)
{
returnValue=false;
Console.WriteLine("Exception occurred. " + ex.Message);
}
return returnValue;
}
}
Above code may not be unsafe for exception handling. I made it shorter for your easier understanding. Please go to http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.impersonate(VS.71).aspx for more information.