【发布时间】:2018-03-28 03:00:09
【问题描述】:
我需要在我的 c++ 应用程序中模拟不同的用户。我正在使用以下代码。
try {
IntPtr tokenHandle = IntPtr(0);
bool returnValue = LogonUser(username, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, &tokenHandle);
if (false == returnValue) {
int ret = Marshal::GetLastWin32Error();
throw gcnew System::ComponentModel::Win32Exception(ret);
}
WindowsIdentity^ newId = gcnew WindowsIdentity(tokenHandle);
WindowsImpersonationContext^ impersonatedUser = newId->Impersonate();
//TODO access file with impersonated user rights
impersonatedUser->Undo(); // Stop impersonating the user.
if (tokenHandle != IntPtr::Zero) CloseHandle(tokenHandle); // Free the tokens.
}
catch(Exception^ ex){
}
登录用户函数对于 c++ 控制台应用程序返回 true,但对于可视 c++ 应用程序返回 false。这两个项目都使用公共语言运行时支持。这两个项目具有相同的包含和引用。
【问题讨论】:
-
它不起作用怎么办?
-
对于控制台应用程序登录操作返回true,但对于visual c++应用程序返回false。
-
你是用同一个用户执行的吗?来自 MSDN:“如果函数失败,则返回零。要获取扩展错误信息,请调用 GetLastError。” GetLastError 返回什么?
-
是的,我使用的是相同的用户凭据。 GetLastError 函数的返回值为 ERROR_ENVVAR_NOT_FOUND。
标签: c++ authentication impersonation file-access windows-identity