0

Im trying to impersonate a user from a windows forms application through the following code:

public void Impersonate()
{
    //elevate privileges before doing file copy to handle domain security
    WindowsImpersonationContext impersonationContext = null;
    IntPtr userHandle = IntPtr.Zero;
    const int LOGON32_PROVIDER_DEFAULT = 0;
    const int LOGON32_LOGON_INTERACTIVE = 2;
    string domain = ConfigurationManager.AppSettings["ImpersonationDomain"];
    string user = ConfigurationManager.AppSettings["ImpersonationUser"];
    string password = ConfigurationManager.AppSettings["ImpersonationPassword"];

    try
    {
        // if domain name was blank, assume local machine
        if (domain == "")
            domain = System.Environment.MachineName;

        // Call LogonUser to get a token for the user
        bool loggedOn = LogonUser(user,
                                    domain,
                                    password,
                                    LOGON32_LOGON_INTERACTIVE,
                                    LOGON32_PROVIDER_DEFAULT,
                                    ref userHandle);

        if (!loggedOn)return;

        // Begin impersonating the user
        impersonationContext = WindowsIdentity.Impersonate(userHandle);

        PrintReceipt();
    }
    catch (Exception ex)
    {
        MessageBox.Show("Exception impersonating user: " + ex.Message);
    }
    finally
    {
        // Clean up
        if (impersonationContext != null)
        {
            impersonationContext.Undo();
        }

        if (userHandle != IntPtr.Zero)
        {
            CloseHandle(userHandle);
        }
    }
}

The program is started through a shortcut pointing to a network share and the machine is running Windows7 32 bits.

But the program is throwing a BadImageFormatException on the line:

impersonationContext = WindowsIdentity.Impersonate(userHandle);

The exact same code does work from a console application and I've tried compiling the exe as 'Any CPU' and x86.

Im out of clues, does anyone know what can be done?

Serve Laurijssen
  • 9,266
  • 5
  • 45
  • 98
  • Does sound like your compiling your form to x64 and your x86 setting for the form might be incorrect. Try going into properties for your form project, set target CPU to AnyCPU and if you have a "Prefer 32 bit check box, then mark that one to see if it helps? – Allan S. Hansen Mar 26 '14 at 10:10
  • unfortunately we use VS2010 which doesnt have that option – Serve Laurijssen Mar 26 '14 at 10:15
  • 1
    Use the Fusion Log viewer to identify if the assemblyloader picks up an assembly from an unexpected location. http://msdn.microsoft.com/en-us/library/e74a18c4(v=vs.110).aspx – rene Mar 26 '14 at 10:58

0 Answers0