-1

我需要在我的C++应用程序中模拟不同的用户。我正在使用以下代码。模拟visual 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,但对于visual C++应用程序返回false。这两个项目都使用公共语言运行时支持。两个项目都有相同的包含和引用。

+0

它怎么样?用于控制台应用程序的 – Mark

+0

登录操作返回true,但对于visual C++应用程序返回false。 –

+0

你是否用同一个用户执行过这两个操作?从MSDN:“如果函数失败,它将返回零。要获得扩展的错误信息,请调用GetLastError。” GetLastError返回什么? – willll

回答

0

问题是visual C++项目是win32项目。它已经包含登录功能。所以我不需要.net模拟功能。以下代码修复了我的isue。

 HANDLE tokenHandle = INVALID_HANDLE_VALUE; 
     bool returnValue = LogonUser(L"username", L"domain", L"password", LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, &tokenHandle); 

     if (false == returnValue) { 
      int ret = GetLastError(); 
      throw gcnew System::ComponentModel::Win32Exception(ret); 
     } 

     bool res = ImpersonateLoggedOnUser(tokenHandle); 

     //Access file here 

     CloseHandle(tokenHandle);