visualc中的模拟&x2B+; 我需要在我的C++应用程序中模拟不同的用户。我正在使用以下代码来完成此操作 try { IntPtr tokenHandle = IntPtr(0); bool ret

visualc中的模拟&x2B+; 我需要在我的C++应用程序中模拟不同的用户。我正在使用以下代码来完成此操作 try { IntPtr tokenHandle = IntPtr(0); bool ret,c++,authentication,impersonation,file-access,windows-identity,C++,Authentication,Impersonation,File Access,Windows Identity,visualc中的模拟&x2B+; 我需要在我的C++应用程序中模拟不同的用户。我正在使用以下代码来完成此操作 try { IntPtr tokenHandle = IntPtr(0); bool returnValue = LogonUser(username, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, &tokenHandle);

visualc中的模拟&x2B+; 我需要在我的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。这两个项目都使用公共语言运行时支持。两个项目都有相同的引用和引用。

< P>问题是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);

但是,对于控制台应用程序登录操作返回true,但是对于VisualC++应用程序返回false。您是否使用同一个用户执行这两个操作?来自MSDN:“如果函数失败,则返回零。若要获取扩展错误信息,请调用GetLastError。”GetLastError返回的是什么?是的,我使用的是相同的用户凭据。GetLastError函数的返回值为ERROR\u ENVVAR\u NOT\u FOUND。