1

I need to save file on a unc location using .net core web api. The location could be accessed with correct username & password combo. Following piece of code does not work, I mean when I try to create directory.I am afraid I am not passing username and password correct way. Could someone look into this please.

try
{

    var credential = new NetworkCredential("username", "password", "\\\\location\\Test");
    var testCache = new CredentialCache
    {
        { new Uri("\\\\location\\test"), "Basic", credential }
    };

    var folder = GetDestinationFolder(DateTime.Now, "\\\\location\\test");
    Directory.CreateDirectory(folder); // it throws exception saying access to the path is denied    
}
catch (Exception ex)
{
    var exxx = ex.Message;
}
Daniel
  • 976
  • 5
  • 14
Gautam
  • 363
  • 1
  • 4
  • 15

1 Answers1

1

By default, the credentil is inhertied from the IIS Application Pool. You could run your application under the user account which has the permission to access the unc path.

For another workaround, you could try

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
        int dwLogonType, int dwLogonProvider, out SafeAccessTokenHandle phToken);

    const int LOGON32_PROVIDER_DEFAULT = 0;
    //This parameter causes LogonUser to create a primary token. 
    const int LOGON32_LOGON_INTERACTIVE = 2;
    // Call LogonUser to obtain a handle to an access token. 
    SafeAccessTokenHandle safeAccessTokenHandle;

    [HttpGet, Route("success")]
    public string Success()
    {
        bool returnValue = LogonUser("username","domain" ,"password",
            LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
            out safeAccessTokenHandle);

        WindowsIdentity.RunImpersonated(safeAccessTokenHandle, () =>
        {
            var folder = @"\\unc path";
            Directory.CreateDirectory(folder); // it throws exception saying access to the path is denied    
        });
        return "Success Response";
    }        
}
Edward
  • 28,296
  • 11
  • 76
  • 121
  • I understand it answers my question.I will implement this right away and update you . Meanwhile, will several connection to UNC at a time be allowed using this? – Gautam Feb 22 '19 at 19:51