Validate Windows Domain Account in C#
In C# we can validate windows domain account using following code snippet.
public class WinAPI{
// Use NTLM security provider to check
public const int LOGON32_PROVIDER_DEFAULT = 0x0;
// To validate the account
public const int LOGON32_LOGON_NETWORK = 0x3;
// API declaration for validating user credentials
[DllImport("advapi32.dll", SetLastError = true)] public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out int phToken);
//API to close the credential token
[DllImport("kernel32", EntryPoint="CloseHandle")] public static extern long CloseHandle (long hObject);
};
int hToken=2;
bool ret = WinAPI.LogonUser(strUserName,strDomain,strPwd, WinAPI.LOGON32_LOGON_NETWORK ,
WinAPI.LOGON32_PROVIDER_DEFAULT,
out hToken);
if(ret==true)
{
MessageBox.Show (" Valid Windows domain User ");
WinAPI.CloseHandle (hToken);
}
else
{
MessageBox.Show (" Not an valid Windows domain User ");
}
Explanation
We call LogonUser Win32 API to validate the user credentials. The class WinAPI declares the required Win32 API's and the constants used.
LogonUser takes username, password and password as plain text and validates the user name against the domain with the given password, if the user name is correct then it returns a handle to the user token in hToken out parameter which can be used by the user to Impersonate or create process using his account. If this is not used then hToken should be closed using CloseHandle Win32 API.