Hello Everybody
I'm writing an application that allows to impersonate a user if required.
However, the impersonation keeps failing with message: "Logon failure: unknown user name or bad password".
Even the error sounds pretty clear, it can't be the case, cause the credentials are valid and I'm able to logon to the domain using the given credentials. I also tried different examples, which return the same error
MSDN Example[
^]
or
A Complete Impersonation Demo in C#.NET[
^]
or
User Impersonation in .NET[
^]
Can anybody point-out what I'm doing wrong? The machine I'm testing on it not joined to any domain though. Could that be the problem?
Here's the code I'm using:
public Impersonation(string domain, string username, string password, LogonType LOGON_TYPE, LogonProvider LOGON_PROVIDER)
{
bool ok = LogonUser(username, domain, password, (int)LOGON_TYPE, (int)LOGON_PROVIDER, out this._handle);
if (!ok)
{
int ret = Marshal.GetLastWin32Error();
throw new System.ComponentModel.Win32Exception(ret);
}
this._context = WindowsIdentity.Impersonate(this._handle.DangerousGetHandle());
}
public void Dispose()
{
this._context.Dispose();
this._handle.Dispose();
}
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);
The calling method:
try
{
_slImpersonation = new Impersonation(tbx_Domain.Text, tbx_UserName.Text, tbx_Password.Text, LogonType.LOGON32_LOGON_INTERACTIVE, LogonProvider.LOGON32_PROVIDER_DEFAULT);
toolStripStatusLabel1.Text = "Impersonation succeeded";
_slImpersonation.Dispose();
_slImpersonation = null;
}
catch (Exception exp)
{
toolStripStatusLabel1.Text = "Impersonation failed";
MessageBox.Show(this, exp.Message, "Error", MessageBoxButtons.OK);
_slImpersonation = null;
toolStripStatusLabel1.Text = "";
}
Can anybody explain why this keeps failing although the credentials are valid?
Thanks very much for your answers