Reputation: 11
I am trying to perform file operations (upload, download, delete) in a user's file system using impersonation in C#. After researching, I came across the WindowsIdentity.RunImpersonated
method, which I’m using to delegate authority for file operations.
However, I am encountering an Access Denied error. Below is the relevant code I have implemented:
public class ImpersonationManager
{
private SafeAccessTokenHandle _safeAccessTokenHandle;
private readonly string _domainName;
private readonly string _userName;
private readonly string _password;
[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);
public ImpersonationManager(string domainName, string userName, string password)
{
_domainName = domainName;
_userName = userName;
_password = password;
}
public SafeAccessTokenHandle GetSafeAccessTokenHandle()
{
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
try
{
bool returnValue = LogonUser(_userName, _domainName, _password,
LOGON32_PROVIDER_DEFAULT, LOGON32_LOGON_INTERACTIVE,
out _safeAccessTokenHandle);
if (!returnValue)
{
int ret = Marshal.GetLastWin32Error();
throw new System.ComponentModel.Win32Exception(ret, $"LogonUser failed with error code : {ret}");
}
}
catch (Exception ex)
{
throw;
}
return _safeAccessTokenHandle;
}
}
public async Task<bool> UploadFileAsync(string filePath = null, File file = null, Stream fileStream = null)
{
if (file == null)
throw new ArgumentNullException(nameof(file));
if (fileStream == null)
throw new ArgumentNullException(nameof(fileStream));
SafeAccessTokenHandle safeAccessTokenHandle = GetSafeAccessTokenHandleAsync();
WindowsIdentity.RunImpersonated(safeAccessTokenHandle,() =>
{
var fileName = file.FileName;
try
{
using (FileStream destinationStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
fileStream.CopyTo(destinationStream);
return true;
}
}
catch (Exception ex)
{
throw;
}
});
return true;
}
Upvotes: 1
Views: 49