Visual C++ 中的模拟

Impersonation in visual c++

我需要在我的 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){
    }

登录用户函数 returns 对于 C++ 控制台应用程序为真,但对于 Visual C++ 应用程序为 returns 为假。这两个项目都使用公共语言运行时支持。两个项目都有相同的包含和引用。

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

        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);