/// <summary> /// Impersonates the authorized user. /// </summary> /// <param name="user"></param> /// <returns></returns> public static WindowsImpersonationContext StartImpersonateUser(ImpersonateUser user) { IntPtr logonToken = new IntPtr(0); WindowsImpersonationContext impersonatedUser = null; bool b = LogonUser(user.username, user.domain, user.password, user.logontype, 0, ref logonToken); if (b) { try { WindowsIdentity windowsIdentity = new WindowsIdentity(logonToken); // Create a WindowsImpersonationContext object by impersonating the Windows identity. impersonatedUser = windowsIdentity.Impersonate(); } catch (Exception ex) { throw new Exception(ex.Message); } } return impersonatedUser; }
/// <summary> /// Starts eam service specified by service name by using access right of the user impersonated by system. /// </summary> /// <param name="serviceName"></param> /// <param name="timeout"></param> /// <param name="user"></param> public void StartService(string serviceName, TimeSpan timeout,ImpersonateUser user) { WindowsImpersonationContext impersonateUser = StartImpersonateUser(user); ServiceController service = new ServiceController(serviceName); if (service.Status == ServiceControllerStatus.Stopped) try { service.Start(); } catch (Exception ex) { throw new Exception(ex.Message); } StopImpersonateUser(impersonateUser); try { service.WaitForStatus(ServiceControllerStatus.Running, timeout); } catch (System.ServiceProcess.TimeoutException) { throw new Exception("service did not respond to the start command in a timely manner"); } }
/// <summary> /// if logon user has role as administrator, return token for this user /// else return 0 /// </summary> /// <param name="user"></param> /// <returns></returns> public static bool IsAuthorizedUser(ImpersonateUser user) { bool check = false; IntPtr logonToken = new IntPtr(0); bool b = LogonUser(user.username, user.domain, user.password, user.logontype, 0, ref logonToken); if (b) { WindowsIdentity identity = new WindowsIdentity(logonToken); WindowsPrincipal principal = new WindowsPrincipal(identity); if (principal.IsInRole(WindowsBuiltInRole.Administrator)) check = true; } return check; }