我在我的程序中使用Impersonation。我没有任何问题。但是,当我创建Windows服务时,我在模仿时遇到异常。可能是什么问题?在我的帐户中,我可以成功应用模拟,但Windows服务在本地系统帐户上运行。这是一个问题吗?
这是我的代码:
public enum SECURITY_IMPERSONATION_LEVEL : int
{
SecurityAnonymous = 0,
SecurityIdentification = 1,
SecurityImpersonation = 2,
SecurityDelegation = 3
}
public static WindowsImpersonationContext ImpersonateUser(string sUsername, string sDomain, string sPassword)
{
// initialize tokens
IntPtr pExistingTokenHandle = new IntPtr(0);
IntPtr pDuplicateTokenHandle = new IntPtr(0);
pExistingTokenHandle = IntPtr.Zero;
pDuplicateTokenHandle = IntPtr.Zero;
// if domain name was blank, assume local machine
if (sDomain == "")
sDomain = System.Environment.MachineName;
try
{
string sResult = null;
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
// get handle to token
bool bImpersonated = LogonUser(sUsername, sDomain, sPassword,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle);
// did impersonation fail?
if (!bImpersonated)
{
//Giriş yapılırken hata ile karşılaşıldı
Helper.ShowErrorMsg(ErrorAndInfoMessages.ErrorOnLogon);
return null;
}
// Get identity before impersonation
sResult += "Before impersonation: " + WindowsIdentity.GetCurrent().Name + "\r\n";
bool bRetVal = DuplicateToken(pExistingTokenHandle, (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, ref pDuplicateTokenHandle);
// did DuplicateToken fail?
if (!bRetVal)
{
//DuplicateToken() failed
Helper.ShowErrorMsg(ErrorAndInfoMessages.ErrorTokenFailed);
return null;
}
else
{
// create new identity using new primary token
WindowsIdentity newId = new WindowsIdentity(pDuplicateTokenHandle);
WindowsImpersonationContext impersonatedUser = newId.Impersonate();
// check the identity after impersonation
sResult += "After impersonation: " + WindowsIdentity.GetCurrent().Name + "\r\n";
return impersonatedUser;
}
}
catch (Exception ex)
{
Helper.ShowErrorMsg("ImpersonateUser Hata: " + ex.Message);
return null;
}
finally
{
// close handle(s)
if (pExistingTokenHandle != IntPtr.Zero)
CloseHandle(pExistingTokenHandle);
if (pDuplicateTokenHandle != IntPtr.Zero)
CloseHandle(pDuplicateTokenHandle);
}
}
以下是例外: 当应用程序未在UserInteractive模式下运行时显示模式对话框或表单不是有效操作。指定ServiceNotification或DefaultDesktopOnly样式以显示来自服务应用程序的通知。
我也试过用我的帐户运行Windows服务但没有任何改变。
答案 0 :(得分:1)
尝试使用LOGON32_LOGON_NETWORK = 3而不是LOGON32_LOGON_INTERACTIVE = 2。 根据{{3}},LOGON32_LOGON_INTERACTIVE适用于将以交互方式使用计算机的用户,因此像Windows服务这样的无人值守进程可能会失败。
我们遇到了同样的问题,上面的更改修复了它。