【问题标题】:Impersonation in visual c++Visual C++ 中的模拟
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-03-23
    • 1970-01-01
    • 2016-02-08
    • 2011-05-12
    • 2014-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    相关资源
    最近更新 更多