可视化 C++ 中的模拟

Impersonation in visual c++

本文关键字:模拟 C++ 可视化      更新时间:2023-10-16

我需要在我的 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。 这两个项目都使用公共语言运行库支持。这两个项目具有相同的包含和引用。

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