title: Impersonate a user in .Net Core
body: <p>I am trying to impersonate a user in .NET core to copy a file directly to shared drive. I have looked it up online and copied and changed code but my Login function does not work.</p>
  
  <p>Here is the code</p>
  
  <pre><code> #region Impersionation global variables
          public const int LOGON32_LOGON_INTERACTIVE = 2;
          public const int LOGON32_PROVIDER_DEFAULT = 0;
  
          [DllImport("advapi32.dll")]
          public static extern int LogonUserA(String lpszUserName,
              String lpszDomain,
              String lpszPassword,
              int dwLogonType,
              int dwLogonProvider,
              ref IntPtr phToken);
          [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
          public static extern int DuplicateToken(IntPtr hToken,
              int impersonationLevel,
              ref IntPtr hNewToken);
  
          [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
          public static extern bool RevertToSelf();
  
          [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
          public static extern bool CloseHandle(IntPtr handle);
          #endregion
  </code></pre>
  
  <p>Impersonate Function</p>
  
  <pre><code> private bool ImpersonateUser(string domain, string userName, string password)
          {
              WindowsIdentity tempWindowsIdentity;
              IntPtr token = IntPtr.Zero;
              IntPtr tokenDuplicate = IntPtr.Zero;
  
  
              if (RevertToSelf())
              {
  //This logonUserA does not run correctly
                  if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
                      LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                  {
                      if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                      {
                          tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
  
                          WindowsIdentity.RunImpersonated(tempWindowsIdentity.AccessToken,() =&gt;
                          {
                              CloseHandle(token);
                              CloseHandle(tokenDuplicate);
                          });
  
                      }
                  }
              }
              if (token != IntPtr.Zero)
                  CloseHandle(token);
              if (tokenDuplicate != IntPtr.Zero)
                  CloseHandle(tokenDuplicate);
              return false;
          }
  
  </code></pre>
  
  <p>LogonUserA function is not logging in correctly. I am passing in domain name, username and password correctly but it still does not work.</p>
  
  <p>Any ideas will be appreciated</p>