-1

I need to impersonate different user in my c++ application. I am using following code to this.

     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){
    }

Logon user function returns true for c++ console application, but returns false for visual c++ application. Both projects are using common language runtime support. Both projects have same includes and references.

doğan
  • 339
  • 1
  • 4
  • 15
  • What about it isn't working? – bgfvdu3w Oct 16 '17 at 14:38
  • for console application logon operation returns true, but for visual c++ application returns false. – doğan Oct 16 '17 at 14:44
  • Did you execute both with the same user ? From MSDN : "If the function fails, it returns zero. To get extended error information, call GetLastError." What GetLastError is returning ? – willll Oct 16 '17 at 15:55
  • Yes I am using same user credentials. The return value of GetLastError function is ERROR_ENVVAR_NOT_FOUND. – doğan Oct 17 '17 at 07:15

1 Answers1

0

The problem is visual c++ project is win32 project. It already contains Logon function. So I don't need .net impersonation functions. The following code fixed my 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);
doğan
  • 339
  • 1
  • 4
  • 15