I'am working on a program which has to check if there is a connection to the NAS and if it's possible to write and read data from it. Checking the connection is not a problem.
I'am running on a Windows Server 2012 and know the credentials from the NAS. I tried impersonating with those credentials but this did not work. I'am always getting the same error. The user name or password is incorrect. But when I connection with the windows explorer with the same credentials it works.
This is my DLL Import and the necessary variables
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain,
String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
// Variables
private IntPtr m_Token;
private WindowsImpersonationContext m_Context = null;
private string m_Domain;
private string m_Password;
private string m_Username;
m_Domain is different to the local domain
This is the actual Impersonation
m_Token = IntPtr.Zero;
bool logonSuccessfull = LogonUser(
m_Username,
m_Domain,
m_Password,
(int)LOGON32_TYPE_NETWORK,
(int)LOGON32_PROVIDER_WINNT50,
ref m_Token);
if (logonSuccessfull == false)
{
int error = Marshal.GetLastWin32Error();
throw new Win32Exception(error);
}
WindowsIdentity identity = new WindowsIdentity(m_Token);
m_Context = identity.Impersonate();
LOGON32_TYPE_NETWORK is equal to 3, LOGON32_PROVIDER_WINNT50 is equal to 3
This code is executed with administrator rights.
This is the error which gets thrown:
System.ComponentModel.Win32Exception (0x80004005): The user name or password is incorrect
This error get's thrown at
if (logonSuccessfull == false)
{
int error = Marshal.GetLastWin32Error();
throw new Win32Exception(error);
}
Is there another way? Or do have to use other LogonType's or LogonProvider?
These I have also tried but also did not work for me.
private const int LOGON32_PROVIDER_DEFAULT = 0;
private const int LOGON32_LOGON_INTERACTIVE = 2;
private const int LOGON32_TYPE_NEW_CREDENTIALS = 9;
When using the LOGON32_TYPE_NEW_CREDENTIALS it doesn't throw an error but the impersonated user does not change at all.