title: How to use impersonation to access a network resource from IIS?
body: <p>I have a WebApi app that needs to access a network share on a different machine and open Crystal Reports files.</p>
  
  <p>I'm using <code>LogonUser</code> and <code>WindowsIdentity.Impersonate</code> to impersonate a user that has rights to the network share using this code (not complete):</p>
  
  <pre><code>SafeTokenHandle safeTokenHandle;
  
  const int LOGON32_PROVIDER_DEFAULT = 0;
  const int LOGON32_LOGON_INTERACTIVE = 2;
  
  bool returnValue = LogonUser(userName, domainName, userPassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);
  
  if (returnValue == false)
  {
      int ret = Marshal.GetLastWin32Error();
      throw new System.ComponentModel.Win32Exception(ret);
  }
  
  using (safeTokenHandle)
  using (var newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
  using (var impersonatedUser = newId.Impersonate())
  { 
      actionToExecute();
  }
  </code></pre>
  
  <p>This works fine when, for example, listing folders or deleting files using managed code (<code>System.IO</code>). However I need to open Crystal Reports files (I have the latest version), and when doing so, I get an exception:</p>
  
  <blockquote>
    <p>Access denied</p>
  </blockquote>
  
  <p>I am assuming that CR is trying to load the file within the context of the Application Pool user.</p>
  
  <p>I would probably get this working if I change the Application Pool user to a domain user with enough rights on the network share. But I want to avoid this solution.</p>
  
  <p>Would using the new <code>WindowsIdentity.RunImpersonated</code> for .NET4.6 help or will it have the same outcome. If yes, is there a way to get CR to run within the supplied user context instead of the Application Pool / AppDomain user?</p>
  
  <p><strong>UPDATE</strong> </p>
  
  <p>I've had partial success by changing the <code>LogonUser</code> parameters to <code>LOGON32_LOGON_NEW_CREDENTIALS</code> and <code>LOGON32_PROVIDER_WINNT50</code>. Then I tested the following:</p>
  
  <ol>
  <li><p>Started the project locally from within VS2017 (so that the WebApi project runs within the local IIS Express context) and accessed the network resource using the client app on my machine. This test was a success.</p></li>
  <li><p>Published the WebApi project on IIS on a separate machine. Started the client (ClickOnce) project on my machine and accessed the same network resource. This test fails.</p></li>
  <li><p>Same as (2) but the client is published and installed on another machine, and accessing it using terminal server. This test fails.</p></li>
  </ol>
  
  <p>Why does the first test succeeds but tests 2 and 3 fail? What should the correct logon parameters be if the supplied ones won't always work?</p>