0

this is my code and I want to know how to use network credentials in my code

 string filePath = Path.Combine(@"\\192.168.5.90\uploads", newfilename);                
     using (var filestream = new FileStream(filePath, FileMode.Create,FileAccess.Write))
     {
      await uploadfile.CopyToAsync(filestream);
     }
      return Ok(newfilename); 
Nader Gliza
  • 3
  • 1
  • 2
  • You're going to have to impersonate the user, which is not trivial and creates a certain set of security risks. You might consider simply [mapping a network drive as a different user](https://superuser.com/questions/727944/accessing-a-windows-share-with-a-different-username) to get the access you need, which would require no code. – John Wu Jul 12 '21 at 20:54

2 Answers2

1

Windows uses the identity of the user running the process of the app for this authentication.

You will need to impersonate an alternative user and execute the code that writes that file in that impersonation context. Look into WindowsIdentity.RunImpersonated method https://learn.microsoft.com/en-us/dotnet/api/system.security.principal.windowsidentity.runimpersonated?view=netcore-3.1

Nick Goloborodko
  • 2,883
  • 3
  • 21
  • 38
0

you can use this link

You can use a impersonator instead:

using (var impersonator = new Impersonator(username, password))
{
    File.Copy(source, destination, true);
}

this is a copy past from our implementation, so please adjust your domain name

using System;
using System.Runtime.InteropServices;
using System.Security.Principal;

public class Impersonator : IDisposable
{
/// <summary>
///     The Impersonator class is used to access a network share with other credentials.
/// </summary>
private readonly WindowsImpersonationContext _impersonatedUser;

private readonly IntPtr _userHandle;

/// <summary>
///     Constructor
/// </summary>
/// <param name="username">The user of the network share</param>
/// <param name="password">The password of the network share</param>
public Impersonator(string username, string password, string userDomain =   "YOURDOMAIN")
{
    _userHandle = new IntPtr(0);
    bool returnValue = LogonUser(username, userDomain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                                 ref _userHandle);
    if (!returnValue)
        throw new ApplicationException(
            "The applications wasn't able to impersonate the user with the specified credentials!");
    var newId = new WindowsIdentity(_userHandle);
    _impersonatedUser = newId.Impersonate();
}

#region IDisposable Members

public void Dispose()
{
    if (_impersonatedUser != null)
    {
        _impersonatedUser.Undo();
        CloseHandle(_userHandle);
    }
}

#endregion

#region Interop imports/constants

public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_LOGON_SERVICE = 3;
public const int LOGON32_PROVIDER_DEFAULT = 0;

[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
public static extern bool LogonUser(String lpszUserName, String lpszDomain, String lpszPassword, int dwLogonType,
                                    int dwLogonProvider, ref IntPtr phToken);

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);

#endregion
}
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 08 '22 at 22:25
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/31488756) – Andrew Halil Apr 11 '22 at 10:29
  • But where to securely store and retrieve the username/password used in impersonation instead of hardcoding them? – Nina Dec 26 '22 at 16:54