c++authenticationimpersonationfile-accesswindows-identity

Impersonation in visual c++


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.


Solution

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